防止bash脚本中的通配符扩展

时间:2013-05-14 00:09:38

标签: bash

我在这里搜索过,但仍然无法找到我的全球问题的答案。

我们有文件“file.1”到“file.5”,如果我们的隔夜处理没问题,每个文件应该包含字符串“completed”。

我认为首先检查是否存在某些文件是件好事,然后我想要查看它们是否找到5个“已完成”的字符串。以下无辜的方法不起作用:

FILES="/mydir/file.*"
if [ -f "$FILES" ]; then
    COUNT=`grep completed $FILES`
    if [ $COUNT -eq 5 ]; then
        echo "found 5"
else
    echo "no files?"
fi

感谢您的任何建议.... Lyle

3 个答案:

答案 0 :(得分:3)

Per http://mywiki.wooledge.org/BashFAQ/004,计算文件的最佳方法是使用数组(设置nullglob选项):

shopt -s nullglob
files=( /mydir/files.* )
count=${#files[@]}

如果你想收集这些文件的名称,你可以这样做(假设是GNU grep):

completed_files=()
while IFS='' read -r -d '' filename; do
  completed_files+=( "$filename" )
done < <(grep -l -Z completed /dev/null files.*)
(( ${#completed_files[@]} == 5 )) && echo "Exactly 5 files completed"

这种方法有点冗长,但即使对于非常不寻常的文件名也能保证工作。

答案 1 :(得分:2)

试试这个:

[[ $(grep -l 'completed' /mydir/file.* | grep -c .) == 5 ]] || echo "Something is wrong"
如果找不到5 completed行,

将打印“有问题”。

更正了缺少的“-l” - 解释

$ grep -c completed file.*
file.1:1
file.2:1
file.3:0

$ grep -l completed file.* 
file.1
file.2

$ grep -l completed file.* | grep -c .
2

$ grep -l completed file.* | wc -l
   2

答案 2 :(得分:0)

你可以这样做以防止通配:

echo \'$FILES\'

但似乎你有一个不同的问题