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 consequent-commands; [elif more-tests; then more-consequents;] [else alternate-path;] fi
The syntax sometimes is enough, but in most cases examples are better, so here we go:
#!/bin/bash # $# 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." else echo "The params: $*" fi
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:
#!/bin/bash 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" else echo "Got unknown OS: $os" fi
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! :-)