I am trying to do an if/then statement, where if there is non-empty output from a ls | grep something command then I want to execute some statements. I am do not know the syntax I should be using. I have tried several variations of this:
if [[ `ls | grep log ` ]]; then echo "there are files of type log";
Well, that’s close, but you need to finish the
ifwithfi.Also,
ifjust runs a command and executes the conditional code if the command succeeds (exits with status code 0), whichgrepdoes only if it finds at least one match. So you don’t need to check the output:If you’re on a system with an older or non-GNU version of
grepthat doesn’t support the-q("quiet") option, you can achieve the same result by redirecting its output to/dev/null:In this particular case, you can do without
grepentirely, sincelsreturns nonzero if it doesn’t find a specified filename, as in D.Shawley’s answer:But in Zsh, or Bash with the
failgloboption set, such a command will error out if the wildcard doesn’t match anything, without ever actually runningls. You can take advantage of that behavior to check without needinglsat all:Or you could set
nullglobinstead:In Ksh, or Bash without either option set, it’s a little more work: