Bash If Else
An if statement runs a block of code only when its test passes. The else block runs when the test fails.
A Passing Test
A test with a value inside the brackets passes. The line inside the block runs.
if [ 1 ]; then
echo "The test passed"
fiThe Else Branch
An empty variable makes the test fail. The else block runs instead.
message=""
if [ "$message" ]; then
echo "Message: $message"
else
echo "No message yet"
fiAdding Elif
The first test fails because the variable is empty. The elif test passes and its block runs.
sunny=""
rainy="yes"
if [ "$sunny" ]; then
echo "Wear sunglasses"
elif [ "$rainy" ]; then
echo "Take an umbrella"
else
echo "Take a light jacket"
fiExample
trip="planned"
booked=""
if [ "$booked" ]; then
echo "Your seat is booked"
elif [ "$trip" ]; then
echo "The trip is planned but not booked"
else
echo "No trip is planned"
fiKey points
- An if statement starts with the word if.
- The word then marks the start of the block.
- The else block runs when the test fails.
- The word elif adds one more test.
- The word fi ends the whole statement.
- A test sits inside square brackets with spaces.
In this example, the first test fails because booked is empty. The elif test passes because trip holds text, so the middle line prints.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which word ends an if statement in Bash?