Billy Moon Billy Moon - 3 months ago 14
Linux Question

Bash shell `if` command returns something `then` do something

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";

Answer

Well, that's close, but you need to finish the if with fi.

Also, if just runs a command and executes the conditional code if the command succeeds (where 'succeeds' just means 'exits with status code 0', which grep does only if it finds at least one match). So you don't need to check the output:

if ls | grep -q log; then echo "there are files of type log"; fi

If you're on a system with an older or non-GNU version of grep that doesn't support the -q ("quiet") option, you can achieve the same result by redirecting its output to /dev/null:

if ls | grep log >/dev/null; then echo "there are files of type log"; fi

But since ls also returns nonzero if it doesn't find a specified file, you can do the same thing without the grep at all, as in D.Shawley's answer:

if ls *log* >&/dev/null; then echo "there are files of type log"; fi

You also can do it using only the shell, without even ls, though it's a bit wordier:

for f in *log*; do 
  # even if there are no matching files, the body of this loop will run once
  # with $f set to the literal string "*log*", so make sure there's really
  # a file there:
  if [ -e "$f" ]; then 
    echo "there are files of type log"
    break
  fi
done 

Although bash has the nullglob option which you can use to simplify that:

shopt -s nullglob
for f in *log*; do
  echo "There are files of type log"
  break
done