linux - while 循环测试 bash 中是否存在具有给定模式的文件

标签 linux bash shell

我想用这样的文件循环检查是否存在具有给定模式的文件:

while [ ! -f "/tmp/?????-Stock.txt" ]
do
  sleep 2
done

如果存在更多文件,如 12aaa-Stock.txt、34aaa-Stock.txt,我会收到类似二元运算符预期的消息错误。

最佳答案

您可以通过使用 for 循环来解决这个问题,例如。

DONE=no
while [ "$DONE" = no ]
do
    for name in /tmp/?????-Stock.txt
    do
        if [ -f "$name" ]
        then
             DONE=yes
             break
        fi
    done
    [ "$DONE" = no ] && sleep 2
done

只要没有找到文件,for 循环就会处理一项(不匹配的模式)。如果找到多个文件,for 循环会在找到第一个匹配项时立即退出。

@chepner请注意,我本可以使用 break 2(旧习难改)。看起来像这样:

while :
do
    for name in /tmp/?????-Stock.txt
    do
        [ -f "$name" ] && break 2
    done
    sleep 2
done

关于linux - while 循环测试 bash 中是否存在具有给定模式的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32180794/

相关文章:

bash - 用户在拨出组中吗?

linux - bash 条件表达式 -x 可以看作是 if 条件吗?

regex - [[ :print:]] means on a directory path? 是什么

shell - 远程传输文件的linux命令和shell脚本

linux - 修复明显损坏的 pdf 并减小文件大小

linux - 如何用shell脚本将tun0的当前IP写入txt文件?

python - 首选项窗口在关闭时销毁 - Glade、Gtk、Python

linux - xargs 可以分隔参数吗?

bash - 将文本文件拆分为多个文件

android - bash/mksh 的 Android 实现中此处文档/字符串的问题