0

在 Unix 中,我有一个类似于以下的代码

find /dir -name "filename*" -type f -print | xargs rm

case "$?" in
     "0") status="SUCCESS";;
      *) status=FAILED";;
esac

它一直在返回 FAILED,我认为这是因为在删除文件完成之前执行了 case 语句。也许如果我在第一条语句之后添加一些等待时间,我可以确定该文件已被完全删除。如果是这样,那么如何在脚本中添加一些等待时间,例如 60 秒?

编辑:我应该提到文件正在被删除,但退出状态不为零。

4

2 回答 2

2

如果有与您的文件规范匹配的奇怪命名的文件,那么您正在做的事情是有问题的。如果将 find 的输出通过管道传输到 xargs,您将遇到由来已久的Parsing LS问题

[ghoti@pc ~/tmp2]$ touch $'one\ntwo.txt' "three four.txt"
[ghoti@pc ~/tmp2]$ find . -name "*txt" -type f -print | xargs rm
rm: ./three: No such file or directory
rm: four.txt: No such file or directory
rm: ./one: No such file or directory
rm: two.txt: No such file or directory

为什么不直接处理你的rminside find

find /dir -name "filename*" -type f -exec rm {} \;

要测试您的结果,您可以抓取$?

find /dir -name "filename*" -type f -exec rm {} \;
result=$?
case "$result" in
etc, etc

(我放入$?了一个变量,以防以后重新使用它会很有用,或者如果其他命令需要find在其返回值被评估的位置之间运行。)

或者您可以直接测试是否成功:

if find /dir -name "filename*" -type f -exec rm {} \;
then
    echo "SUCCESS!"
else
    echo "FAIL!"
fi

更新:

根据评论...如果您不必通过子目录递归,那么 for 循环可能就足够了。

for file in *.txt; do
  if ! rm "$file"; then
    echo "ERROR: failed to remove $file" >&2
  fi
done

或者,如果您不需要在单个文件上生成错误的粒度:

rm *.txt || echo "ERROR" >&2

我不认为我可以让它变得更小。:-P

于 2012-08-22T04:37:20.717 回答
1

首先,我假设“类似于以下内容”包括在字符串文字周围使用两个引号。FAILED如果没有,您可能应该先解决这个问题。

在前面的过程完成之前开始的可能性很小case没有使用&在后台运行某些东西,这不是 UNIX 方式:-)

您应该做的第一件事是将case语句替换为:

rc=$?
case $rc in
    0) status="SUCCESS";;
    *) status="FAILED"; echo rc=$rc;;
esac

看看返回码实际上是什么。然后查找man xargs$?始终是管道中最后一件事的退出代码),它显示了可能的值及其可能的原因。例如:

EXIT STATUS
    xargs exits with the following status:
         0 if it succeeds
       123 if any invocation of the command exited with status 1-125
       124 if the command exited with status 255
       125 if the command is killed by a signal
       126 if the command cannot be run
       127 if the command is not found
         1 if some other error occurred.
    Exit codes greater than 128 are used by the shell to indicate
    that a program died due to a fatal signal.
于 2012-08-21T02:47:29.640 回答