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 in bash.

Check arguments in bash script

We can use conditional programming to improve our previous example,, since it contained a little problem. It expects a name in $1 without checking if it actually gets one. Let’s fix this:

Check arguments in your Bash script

If that didn’t work, here’s a static version of the same code:

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

The test command in bash

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 so it really aids in conditional programming. The full list can be seen when you enter man test on the command line. 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. After all, in the old days, we didn’t have the Internet to google everything…

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

Compare two values in Bash

Here’s the static version in case that didn’t work:

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

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

Although the else-part is optional, you always need to end with a fi.

About Erik van Baaren

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! Writing good articles takes time and effort. Did you like this tutorial? You can buy him a coffee to show your appreciation.

Leave a Comment