czchlong
czchlong

Reputation: 2574

How to check if files matching a regex exist in a directory in bash script?

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

Answers (5)

Alberto Salvia Novella
Alberto Salvia Novella

Reputation: 1250

Bash has a built-in command for that:

compgen -G [GLOB]

Upvotes: 0

Waxo
Waxo

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

Michael Krelin - hacker
Michael Krelin - hacker

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

fge
fge

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

ajreal
ajreal

Reputation: 47321

Use find

A simple example,

find $DIR -type f -name "srv_*.log" 

Upvotes: 6

Related Questions