When bash scripting, you can use conditionals to control which set of commands within the script run. Use
if to start the conditional, followed by the condition in square brackets (
[ ]). Make sure you leave a space between a bracket and the conditional statement!
then begins the code that will run if the condition is met.
else begins the code that will run if the condition is not met. Lastly, the conditional is closed with a backwards
A complete conditional in a bash script uses the following syntax:
if [ $index -lt 5 ] then echo $index else echo 5 fi
Bash scripts use a specific list of operators for comparison. Here we used
-lt which is “less than”. The result of this conditional is that if
$index is less than 5, it will print to the screen. If it is 5 or greater, “5” will be printed to the screen.
Here is the list of comparison operators for numbers you can use within bash scripts:
- Not equal:
- Less than or equal:
- Less than:
- Greater than or equal:
- Greater than:
- Is null:
When comparing strings, it is best practice to put the variable into quotes (
"). This prevents errors if the variable is null or contains spaces. The common operators for comparing strings are:
- Not equal:
For example, to compare if the variables
bar contain the same string:
if [ "$foo" == "$bar" ]
We’ve added two different greetings and a variable to store how many times the user has been greeted before. If this variable is less than 1, we want to use
first_greeting. Otherwise, we want to use
Add a line setting up the
if conditional. Use the
echo to print
$first_greeting if the conditional is met and
$later_greeting otherwise. Be sure to close the if statement.
Run the script in the terminal. Try adjusting the value of
$greeting_occasion to test your