How to check if find command didn't find anything?

Izzy picture Izzy · Aug 6, 2014 · Viewed 30k times · Source

I know that is possible to use for loop with find command like that

for i in `find $something`; do (...) done

but I want to use find command with "if".

I am trying to create progress comments (and log files later) about removed files by my script. I need to check if

find /directory/whatever -name '*.tar.gz' -mtime +$DAYS

found something or not. If not I want to say echo 'You don't have files older than $DAYS days' or something like this ;)

How I can do that in shell script?

Answer

Mark Setchell picture Mark Setchell · Aug 6, 2014

Count the number of lines output and store it in a variable, then test it:

lines=$(find ... | wc -l)
if [ $lines -eq 0 ]; then
...
fi