Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 597
Izzy Avatar asked Aug 06 '14 09:08

Izzy


People also ask

What does find return if nothing is found Linux?

The function and syntax of find() is very much like the Array. filter method, except it only returns a single element. Another difference is when nothing is found, this method returns a value of undefined . So if you only need a single value, use find() !


2 Answers

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 
like image 182
Mark Setchell Avatar answered Sep 20 '22 22:09

Mark Setchell


You want to use find command inside an if condition , you can try this one liner :

 [[ ! -z `find 'YOUR_DIR/' -name 'something'` ]] && echo "found" || echo "not found" 

example of use :

 [prompt] $ mkdir -p Dir/dir1 Dir/dir2/ Dir/dir3                   [prompt] $ ls Dir/  dir1  dir2  dir3  [prompt] $ [[ ! -z `find 'Dir/' -name 'something'` ]] && echo "found" || echo "not found"  not found  [prompt] $ touch Dir/dir3/something  [prompt] $ [[ ! -z `find 'Dir/' -name 'something'` ]] && echo "found" || echo "not found"  found 
like image 38
bachN Avatar answered Sep 21 '22 22:09

bachN