简体   繁体   中英

preventing wildcard expansion in bash script

I've searched here, but still can't find the answer to my globbing problems.

We have files "file.1" through "file.5", and each one should contain the string "completed" if our overnight processing went ok.

I figure it's a good thing to first check that there are some files, then I want to grep them to see if I find 5 "completed" strings. The following innocent approach doesn't work:

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

Thanks for any advice....Lyle

Per http://mywiki.wooledge.org/BashFAQ/004 , the best approach to counting files is to use an array (with the nullglob option set):

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

If you want to collect the names of those files, you can do it like so (assuming 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"

This approach is somewhat verbose, but guaranteed to work even with highly unusual filenames.

try this:

[[ $(grep -l 'completed' /mydir/file.* | grep -c .) == 5 ]] || echo "Something is wrong"

will print "Something is wrong" if doesn't find 5 completed lines.

Corrected the missing "-l" - the explanation

$ 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

You can do this to prevent globbing:

echo \'$FILES\'

but it seems you have a different problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM