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 comma
Exit 0 is easy with find, exit >0 is harder because that usually only happens with an error. However we can make it happen:
if find -type f -exec false {} +
then
echo 'nothing found'
else
echo 'something found'
fi
I wanted to do this in a single line if possible, but couldn't see a way to get find to change its exit code without causing an error.
However, with your specific requirement, the following should work:
find /directory/whatever -name '*.tar.gz' -mtime +$DAYS | grep 'tar.gz' || echo "You don't have files older than $DAYS days"
This works by passing the output of find into a grep
for the same thing, returns a failure exit code if it doesn't find anything, or will success and echo the found lines if it does.
Everything after ||
will only execute if the preceding command fails.
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
Iterating over the output of find
might be dangerous if your filenames contain spaces. If you're sure they don't, you can store the result of find
to an array, and check its size to see there were any hits:
results=( $(find -name "$something") )
if (( ${#results[@]} )) ; then
echo Found
else
echo Not found
fi
for file in "${results[@]}" ; do
# ...
done
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
This worked for me
if test $(find . -name "pattern" | wc -c) -eq 0
then
echo "missing file with name pattern"
fi