Branching with conditional statements
At its core, a conditional statement in Bash is a way to tell your script, “Hey, if this specific thing is true, then go ahead and do this; otherwise, do that.” It’s the foundation of making decisions in your scripts. The most common conditional statements you’ll encounter in Bash are if, else, and elif.
The if statement
The if
statement is the simplest form of conditional statement. It checks for a condition, and if that condition is true, it executes a block of code. Here’s a straightforward example:
#!/usr/bin/env bash USER="$1" if [ $USER == 'steve' ]; then echo "Welcome back, Steve!" fi
This example code can be found in the ch03_conditionals_01.sh
file in this chapter’s folder.
In this example, the script checks whether the current user is steve
based on matching the first command-line argument. If it is, it greets Steve. Notice the syntax here...