【问题标题】:How do I specify an existence condition in an if statement using wildcards?如何使用通配符在 if 语句中指定存在条件?
【发布时间】:2013-04-04 02:41:48
【问题描述】:

我在 Ubuntu 机器上运行的 bash 脚本中有以下语句:

for l in foo_????
do
     # do something with $l
done

如果没有与该模式匹配的文件,这将无法正常工作。

我在 for 循环前面加上:

if [ -f foo_??? ]
then
   for l in foo_???

如果有 0 或 1 个文件与该模式匹配,它会工作,但当有更多文件时会失败,并显示消息 line 4: [: foo_123: binary operator expected

如果有 >= 1 个文件匹配该模式,我需要如何修改此块以仅循环?

【问题讨论】:

    标签: bash if-statement for-loop


    【解决方案1】:

    如果没有与模式匹配的文件并且您不希望循环失败,请设置 nullglob 指令:

    ~/foo $ echo *
    *
    ~/foo $ shopt -s nullglob
    ~/foo $ echo *
    
    ~/foo $ 
    

    if 语句失败的原因与for 循环失败的原因相同:未扩展的 glob 仍然存在。如果您想要脚本的sh 兼容版本,您可以使用if 语句代替nullglob 指令,但您必须对其进行调整:

    for file in foo_???; do
        if [ -f "$file" ]; then
            …
        fi
    done
    

    【讨论】:

      【解决方案2】:

      而不是测试您已正确扩展的模式是否正确,您使用一些结构来确保您只获得与您的模式匹配的现有文件。

      例如

       find . -maxdepth 1 -type f -name "foo_???" | while read file
       do
           ...
       done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 2016-05-28
        • 2018-06-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多