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 example contained a little problem. It expects a name in $1 without checking if it actually gets one. Let’s fix this:

if test -z "$1"
  echo "Usage: $0 <Your name>"
  echo "Hello $1, from $0"

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

$ ./
Usage: ./ <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:

for i in {1..10}
  if test $i -eq 3 
    echo "I found the 3!"

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!