3

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.

5 Answers 5

6

Use find

A simple example,

find $DIR -type f -name "srv_*.log" 
Sign up to request clarification or add additional context in comments.

1 Comment

Those systemd PrivateTmp are easier to find in a script than I thought… I wanted to find where my files went that I created in /tmp using PHP and can easily find them with for dirname in `find /tmp -type d -name "systemd-private-*-apache2.service-*" `; do nemo "admin://$dirname/tmp" done
2

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.

3 Comments

Hi fge, could you please explain the "2>/dev/null" and how it works? Thanks.
It discards stderror, though you really don't need to run ls for this purpose in bash. And actually it will not work if you happen to have files with spaces in them.
It redirects stderr to /dev/null. You must first understand that even with your first command, it would have worked: ls puts its result to stdout by default, and it outputs only errors to stderr. If you do A=$(ls nonexistingfile); echo $A you will see that the echo returns nothing, whether you add 2>/dev/null to the substitution or not.
1

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

Comments

1

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

Comments

0

Bash has a built-in command for that:

compgen -G [GLOB]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.