Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Bash if else


Bash if else is the most fundamental control flow statement used almost in every script. In the following Bash tutorial we show how to use if-else on examples!


The syntax of Bash if else statement is the following:

if tests; then
[elif more-tests; then
[else alternate-path;]

The syntax sometimes is enough, but in most cases examples are better, so here we go:

# $# is the number of parameters passed to the script
# "-eq" is for numeric comparison and means "equals"
if [ $# -eq 0 ]; then
    echo "No parameters passed to the script."
    echo "The params: $*"

One thing worth noting is that test command is in square brackets “[]” and is separated from them by one space on each side.

Test for two conditions:

os=$(uname -s)
# "-n" returns true if given string is not empty
# "==" is for string equality comparison
if [ -n "$os" ] && [ "$os" == "Linux" ]; then
  echo "Got Linux!"
elif [ "$os" == "darwin" ]; then
  echo "I'm on a Mac"
  echo "Got unknown OS: $os"

Note that $os variable is within quotes during the tests. It’s needed, because if the var would be empty you would have “[ -n ]” as a test, which is incorrect syntax.

Another important thing is that in Bash commands on the same line have to be separated by semicolon “;”. This is why there’s a semicolon before then part of if statement. If you put then on the second line you won’t need to put semicolon.

In other tutorials we’ll explore different ways to compare things in Bash. Stay tuned! :-)

Share with the World!