[
and test
are synonyms (except [
requires ]
), so you don't want to use [ test
:
[ -x /bin/cat ] && echo 'cat is executable'
test -x /bin/cat && echo 'cat is executable'
test
returns a zero exit status if the condition is true, otherwise nonzero. This can actually be replaced by any program to check its exit status, where 0 indicates success and non-zero indicates failure:
# echoes "command succeeded" because echo rarely fails
if /bin/echo hi; then echo 'command succeeded'; else echo 'command failed'; fi
# echoes "command failed" because rmdir requires an argument
if /bin/rmdir; then echo 'command succeeded'; else echo 'command failed'; fi
However, all of the above examples only test against the program's exit status, and ignore the program's output.
For find
, you will need to test if any output was generated. -n
tests for a non-empty string:
if [[ -n $(find /var/log/crashes -name "app-*.log" -mmin -5) ]]
then
service myapp restart
fi
A full list of test arguments is available by invoking help test
at the bash
commandline.
If you are using bash
(and not sh
), you can use [[ condition ]]
, which behaves more predictably when there are spaces or other special cases in your condition. Otherwise it is generally the same as using [ condition ]
. I've used [[ condition ]]
in this example, as I do whenever possible.
I also changed `command`
to $(command)
, which also generally behaves similarly, but is nicer with nested commands.
You can do:
find . -exec ./is_dir.py {} \; -o -print
It will list everything that is not a directory. Assuming that is_dir.py
is executable (chmod +x is_dir.py
) and contains something like:
#!/usr/bin/env python
import sys
import os
if os.path.isdir(sys.argv[1]):
sys.exit(0)
sys.exit(1)
And if is_dir.py
generates output of its own, you can do:
rm -f nondir.lst
find . -exec ./is_dir.py {} \; -o -exec echo {} >> nondir.lst \;
so that its outoput doesn't get mixed with the list of names for which is_dir.py
fails.
Best Answer
If you know you have GNU find, use
-quit
to make it stop after the first match.Portably, pipe the output of
find
intohead -n 1
. That wayfind
will die of a broken pipe after a few matches (when it's filledhead
's input buffer).Either way, you don't need
wc
to test whether a string is empty, the shell can do it on its own.