用于检查glob模式是否与任何文件匹配的shell脚本

时间:2017-06-13 06:21:54

标签: bash shell glob

我编写了一个shell脚本来检查二进制文件是否存在:

#!/usr/local/bin/bash

if [ -e "/path/to/a/binary/file/app.bin" ]; then 
     echo "INFO: application has been built successfully" 
else 
     echo "ERROR: application couldn't be built". 
fi

它工作正常并给出预期的结果。但是,如果有许多具有相似名称的应用程序(例如app1.bin, app2.bin等)并且我想测试"app*.bin" if条件失败:

#!/usr/local/bin/bash

    if [ -e "/path/to/a/binary/file/app*.bin" ]; then 
         echo "INFO: application has been built successfully" 
    else 
         echo "ERROR: application couldn't be built". 
    fi

如何更正if条件以搜索app作为名称的任何二进制文件的存在,即app*.bin

2 个答案:

答案 0 :(得分:1)

glob匹配在引号内不起作用。即使您确实删除了它,如果从glob匹配返回多个文件,则条件将失败,因为-e仅适用于单个文件。

bash中你可以这样做,

# the nullglob will let the unmatched glob to handled properly
shopt -s nullglob
fileList=(/path/to/a/binary/file/app*.bin)

if [ "${#fileList[@]}" -ge 1 ]; then
     echo "INFO: application has been built successfully" 
else
     echo "ERROR: application couldn't be built". 
fi

# This line is optional. This is just to ensure the nullglob option is 
# reset after our computation
shopt -u nullglob

答案 1 :(得分:1)

另一种方法是使用compgen -G:它会生成一个匹配文件列表,如果没有匹配,它将以错误状态退出。使用compgen,您需要引号以防止扩展。

if compgen -G "/path/to/a/binary/file/app*.bin" > /dev/null; then 
     echo "INFO: application has been built successfully" 
else 
     echo "ERROR: application couldn't be built". 
fi