06. If-else statements if, then, elif, else, fi

Just like any other language, the shell provides if-else statements to handle logic flow. However, the syntax is quite different - let's see how.

No curly braces!

Instead of curly braces or indentations to enclose logical constructs, the shell encloses if-statements within its keywords if, then, else, and fi. There is also the elif keyword that is the shorthand for else-if.

if command; then
  # If test condition returns exit status of 0 (success)
elif another command; then
  # Another command is true
else
  # Both commands have exit status not 0
fi

Notice anything different from other programming languages? Instead of using some logical expression bound by parentheses, the shell runs commands and checks their exit statuses! This concept may seem foreign and strange at first, but it'll grow on you with practice.

Be sure to get this concept down since it's used in loops as well! It can be confusing since many if statements use bracket notations [], which look like syntax. However, recall that the open bracket [ is just a shortcut for the test command.

Boolean Constructs

When stringing together a group of test commands, use the following syntax:

if [ $value -lt 2 ] && [ $value -gt 0 ]; then
  # value is between 0 and 2
fi

Sample script - flip a coin!

Now that we know enough control flow logic, let's create a simple coin tossing game! We'll have the user pick heads or tails, and the shell toss a coin. If the user is correct, then he/she wins; if not, he/she loses.

Try implementing it on your own with what we have learned thus far, then compare your answer below.

#!/bin/sh
 
printf "Choose (h)eads or (t)ails: "
read user_choice
 
# Make sure user chooses between heads or tails
if [ $user_choice != h ] && [ $user_choice != t ]; then
  echo "Invalid choice. Defaulting to (h)eads."
  user_choice=h
fi
 
# Value of 1 is heads, 2 is tails
computer_choice=$((RANDOM % 2 + 1))
 
if [ $computer_choice -eq 1 ]; then
  echo "Computer chose heads."
else
  echo "Computer chose tails."
fi
 
if [ $computer_choice -eq 1 ] && [ $user_choice = h ]; then
  # Correct
  echo "You win!"
elif [ $computer_choice -eq 1 ] && [ $user_choice = t     | ]; then
  # Incorrect
  echo "You lose!"
elif [ $computer_choice -eq 2 ] && [ $user_choice = t ]; then
  # Correct
  echo "You win!"
else 
  # Incorrect
  echo "You lose!"
fi

Great! You're well on your way to becoming a shell scripting master. Let's move onto case statements.

Take your Linux skills to the next level!

The Linux Command Line

Take your Linux skills to the next level! Try Linux & UNIX

The Linux Command Line takes you from your very first terminal keystrokes to writing full programs in Bash, the most popular Linux shell. Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with regular expressions, and more.

$ Check price
39.9539.95Amazon 4.5 logo(274+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Ad