Home > Mobile >  Test if the find command found files or not
Test if the find command found files or not

Time:07-23

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

CodePudding user response:

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

CodePudding user response:

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 -printf '%f\n')" && [ -n "${filedir}" ]; then
        printf 'Found: %s\n' "${filedir}"
else
        printf 'Oops! Found no file matching *.sql.gz!\n' >&2
fi
  • Related