Bash Conditional Programming

Sometimes you only want to run a command if a certain condition is true. For this, we have the if… then… else…fi construct.

Our previous arguments.sh example contained a little problem. It expects a name in $1 without checking if it actually gets one. Let’s fix this:

#!/bin/bash
if test -z "$1"
then
  echo "Usage: $0 <Your name>"
else
  echo "Hello $1, from $0"
fi

With test -z we can check if a variable’s length is zero. If that is the case, we print some friendly usage instructions:

$ ./arguments.sh
Usage: ./arguments.sh <Your name>

The test command can test for many things. The full list can be seen when you enter

$ man test

That’s right, you don’t need Google for everything! Using man-pages is part of being a command-line ninja! You’ll find that there’s a man page for pretty much everything you can do in your terminal.

Here is one more example in which we compare two values to see if they are the same:

#!/bin/bash
for i in {1..10}
do
  if test $i -eq 3 
  then
    echo "I found the 3!"
  fi
done

This loop runs for 10 iterations and checks if $i is equal to 3 each time. Can you predict the output?

As you can see, the else-part is optional, however, you always need to end with a fi.

Please help us and share this article

About the author

Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He's been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python!