nick
nick

Reputation: 119

Test if the find command found files or not

I have a simple script to check a file of today's date. In the below example, the else condition is ignored if the file is not found. Why so?

if filedir=$(find . -type f -name "*.sql.gz"  -mtime -1 -printf "%f\n"); then
        echo $filedir
else
        echo "oops"
fi

Upvotes: 2

Views: 1359

Answers (2)

Léa Gris
Léa Gris

Reputation: 19555

As Ljm Dullaart explained earlier, the find command does not return a specific code, when no file match patterns or rules.

Though, You may test it found a match, by checking the variable filedir is not empty: [ -n "${filedir}" ]

if filedir="$(find . -type f -name '*.sql.gz'  -mtime -1)" && [ -n "${filedir}" ]; then
        printf 'Found: %s\n' "${filedir}"
else
        printf 'Oops! Found no file matching *.sql.gz!\n' >&2
fi

Upvotes: 0

Ljm Dullaart
Ljm Dullaart

Reputation: 4969

find returns an exit-code of 0 if all arguments are processed successfully, and has only a non-zero exitcode if there was an error. The exit code for find does not indicate whether or not files are found.

This is unlike, for example grep. You can see the difference in behaviour when you use

if filedir=$(find . -type f -name "*.sql.gz"  -mtime -1 -printf "%f\n" | grep '.'); then

Upvotes: 3

Related Questions