gpt4 book ai didi

linux - 用于迭代目录内容的 Bash 脚本仅移动当前未被其他进程打开的文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:07:31 26 4
gpt4 key购买 nike

有人将文件上传到我的 Ubuntu 服务器上的目录。

只有当我知道这些文件已完全上传时,我才需要将这些文件移动到最终位置(另一个目录)。

到目前为止,这是我的脚本:

#!/bin/bash

cd /var/uploaded_by_users

for filename in *; do

lsof $filename

if [ -z $? ]; then
# file has been closed, move it
else
echo "*** File is open. Skipping..."
fi

done

cd -

但是它不起作用,因为它说某些文件已打开,但事实并非如此。我以为 $?如果文件已关闭,则为 0,否则为 1,但我认为这是错误的。

我不是 Linux 专家,所以我想知道如何实现这个每 1 分钟在 cron 作业上运行的简单脚本。

最佳答案

[ -z $? ] 检查 $? 是否为零长度。由于 $? 永远不会是空字符串,您的检查将始终失败并导致执行 else 部分。您需要测试数字零,如下所示:

lsof "$filename" >/dev/null; lsof_status=$?
if [ "$lsof_status" -eq 0 ]; then
# file is open, skipping
else
# move it
fi

或者更简单(正如本杰明所指出的):

if lsof "$filename" >/dev/null; then
# file is open, skip
else
# move it
fi

使用否定,我们可以缩短 if 语句(正如 dimo414 指出的那样):

if ! lsof "$filename" >/dev/null; then
# move it
fi

您可以使用 && 进一步缩短它:

for filename in *; do
lsof "$filename" >/dev/null && continue # skip if the file is open
# move the file
done

关于linux - 用于迭代目录内容的 Bash 脚本仅移动当前未被其他进程打开的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43641329/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com