Reputation: 2574
I would like some help in finding a way to check if files matching a certain regex exist in a directory. Currently, I am using the following method, but it will return an error in certain cases:
ls srv_*.log
The above command will result in ls: cannot access srv_*.log: No such file or directory if there are no files in the directory matching the regex.
The regex I am trying to match is "srv_*.log"
Does anyone have any ideas?
Thanks.
Upvotes: 3
Views: 6583
Reputation: 1250
Bash has a built-in command for that:
compgen -G [GLOB]
Upvotes: 0
Reputation: 1976
Assuming you are in the good directory, you can do :
shopt -s nullglob
set -- srv_*.log
if [ $# -gt 0 ]
then
#do your stuff
fi
$#
contains the number of matching files
Upvotes: 1
Reputation: 143071
From bash
manpage:
If the nullglob option is set, and no matches are found, the word is removed. If the failglob shell option is set, and no matches are found, an error message is printed and the command is not executed.
meaning you may want to
shopt -s nullglob
Upvotes: 1
Reputation: 121712
srv_*.log
is not a regex but a glob matcher.
You can just capture the output and redirect stderr to /dev/null:
FILES_LIST="$(ls srv_*.log 2>/dev/null)"
for file in $FILES_LIST; do
#something with $file
done
And you could even do without FILES_LIST
here.
Upvotes: 2