Bash scripts help automate tasks on your machine. The
if elif else statement in bash scripts allows creating conditional cases and responses to specific code results. The
if conditional helps automate a decision-making process during a program.
This article explains what the
if elif else statement is and shows the syntax through various examples.
- A machine with Linux OS.
- Access to the command line/terminal.
- Access to a text editor like Vi/Vim.
What is the Bash if Statement?
In programming, the
if statement is a conditional expression. However, the command tested in the
if statement evaluates based on the exit status. Therefore:
- If the command completes successfully, the exit status is 0.
- If the statement throws an error, the exit status is any number between 1 and 255.
The zero for success and any non-zero value for failure seems counterintuitive. In most other programming languages, zero represents false, and one (or greater) represents true. However, in bash scripting, the UNIX convention returns the exit status instead of a truth value, and the two should not be confused.
Test a sample error command (1 greater than 100) in the terminal by running:
test 1 -gt 100
Check the exit status using the echo command:
The test returns an exit code
1, indicating the expression failed.
Similarly, check a sample command that evaluates successfully (1000 greater than 100) in the terminal with:
test 1000 -gt 100
Print the exit status to confirm the command was successful:
The test returns an exit code
0, showing the command completed without an error.
Bash if Statement Example
Follow the instructions below to create an example bash script using an
1. Open the terminal (CTRL+ALT+T) and create an example script to test how the bash
if statement works:
2. In the script, add the following lines:
echo -n "Please enter a whole number: " read VAR echo Your number is $VAR if test $VAR -gt 100 then echo "It's greater than 100" fi echo Bye!
Each line in the script does the following:
- Lines 1-3 provide instructions to enter a number through the console. The number is read into a variable called
- Line 4 starts the
ifstatement and checks the exit status for the command right after (
$VAR -gt 100).
- Lines 5-6 signals the start of commands to execute only if the statement in line 4 completes successfully (with an exit status 0), meaning we entered a number greater than 100.
- Line 7 signals the end of the
- Line 8 is outside of the statement and runs as expected, regardless of the
4. Next, make the file executable:
chmod +x test_script.sh
5. Lastly, run the script with:
The script outputs a different message based on the entered number. Run the script multiple times and test for other numbers to confirm the behavior.
Bash if Statement Syntax
The basic syntax for a bash
if statement is:
if <commands> then <commands> fi
Each keyword has a specific function:
ifsignals the statement's beginning. The command right after is the one in which the exit status check applies.
thenexecutes the commands only if the previous review completes successfully.
ficloses the if statement.
Enclosing the test command in different brackets results in different execution methods for the
if statement. The table below provides a short description as well as a use case for each bracket type.
|Syntax||What it is||When to use|
|Subshell executed in a subprocess.||When the commands affect the current shell or environment. The changes do not remain when the subshell completes.|
|Bash extension.||Use for arithmetic operations and C-style variable manipulation.|
|POSIX builtin, alias for ||Comparing numbers and testing whether a file exists.|
|Bash extension, an advanced version of single square brackets.||String matching a wildcard pattern.|
Below are example bash scripts that use each bracket type with a more in-depth explanation.
Using single parentheses in bash scripting creates a subshell. When combined with the
if statement, the subprocess finishes before continuing the program. The
if analyzes the exit status and acts accordingly.
if statement with single parentheses syntax looks like the following:
if ( <commands> ) then <commands> fi
Try the example below to see how the sub-process behaves together with the
1. Create the script using Vim:
2. Add the following lines of code to the script:
outer_variable=Defined echo Before if: echo inner_variable = $inner_variable echo outer_variable = $outer_variable if ( echo Inside subshell: inner_variable=Defined echo inner_variable = $inner_variable outer_variable=Changed echo outer_variable = $outer_variable ) then echo After then: echo inner_variable = $iner_variable echo outer_variable = $outer_variable fi echo After fi: echo inner_variable = $inner_variable echo outer_variable = $outer_variable
The program does the following:
- Line 1 creates a variable called
outer_variablein which we store a string
- Lines 2-4 print the variables to the console. At this moment,
outer_variablehas a string stored in it, while
- Line 5 starts the
ifstatement and a sub-process, delimited by single parentheses.
- Line 6-11 store a string inside the
inner_variableand change the
outer_variableto a different string. Both values print to the console, and the sub-process ends with an exit code. In this case, the sub-process ends successfully with an exit code
- Line 12-16 execute after the sub-process and print the variable values. However, the values change back to what they were before the
ifstatement. The sub-process only stores the values locally and not globally.
- Lines 16-19 run after the commands in the
thenclause. The values remain unchanged outside the statement.
3. Save the script and close the editor:
4. Make the script executable:
chmod +x single_parentheses.sh
5. Lastly, run the example to test the results:
The output prints the variable states as the program progresses.
The double-parentheses syntax for a bash
if statement is:
if (( <commands> )) then <commands> fi
The double parentheses construct in bash allows:
- Arithmetic evaluation. Defining a variable as
a=$(( 1+1 ))calculates the equation and sets
- C-style variable manipulation. For example, incrementing variables with
(( a++ )).
When using double-parentheses syntax in an
if statement, the evaluation behaves differently. Suppose the expression evaluates to
0, then the
if test does not pass.
Note: Double parentheses are analogous to most other programming languages, where zero is false and one is true.
Try the following example to see how double parentheses work:
1. Create a bash script in the terminal:
2. Add the following code to double_parentheses.sh:
variable=-2 echo Before first if: $variable if (( variable++ )) then echo Incremented ++ style: $variable fi echo After first if: $variable if (( variable=variable+1 )) then echo Incremented arithmetically $variable fi echo After second if: $variable
Each line number in the script does the following:
- Line 1 defines a variable and sets the value to
- Lines 3-5 increments the value C-style inside double parentheses and checks the value. If the variable is not zero, the if prints a message to the console.
- Lines 8-10 increments the variable by one using regular arithmetic notation and prints a message if the variable is not zero.
3. Save the script and close Vim:
4. Change script permissions to executable:
chmod +x double_parentheses.sh
5. Run the script to see the results:
The single bracket is another name for the
test command and a standard POSIX utility available for all shells. The basic syntax is:
if [ <commands> ] then <commands> fi
The first bash
if example provided in this tutorial (test_script.sh) works equally well with the alternative syntax:
echo -n "Please enter a whole number: " read VAR echo Your number is $VAR if [ $VAR -gt 100 ] then echo "It's greater than 100" fi echo Bye!
Run the script to confirm the output is equivalent. For the complete documentation and details on using bracket syntax, run the man command on the
The double-bracket syntax in bash
if scripts is the best option if portability is not necessary. The double-brackets are superior to single-brackets and include many advanced options. The syntax is:
if [[ <commands> ]] then <commands> fi
Try the example below to see how wildcard string matching works in an
1. Create a shell script file called double_brackets:
2. Add the following code:
if [[ $USER == k* ]] then echo Hello $USER fi echo Bye!
3. The script checks if the starting letter of the username is
k and sends a hello message if it is. Save and close the script:
4. Make the file executable with chmod:
chmod +x double_brackets.sh
5. Run the program with:
Other Types of Bash Conditional Statements
if statement only performs one conditional check. Modify the
if with other types of bash conditionals to create complex assessments.
if else Statement
if else statement provides one method to define different actions based on the output of the checked conditional. The basic syntax is:
if <command> then <commands> else <commands> fi
The following example demonstrates how the
if else conditional works:
1. Create a new script using Vim:
2. Insert the following code into the script:
echo -n "Please enter a whole number: " read VAR echo Your number is $VAR if [ $VAR -gt 100 ] then echo "It's greater than 100" else echo "It's less than 100" fi echo Bye!
The statement checks the command output in line 4 and prints a descriptive message based on the result:
- If the entered number is greater than 100, the program enters line 6 and prints the message.
- If the number is less than 100, the message in the
elseclause (line 8) prints to the console.
3. Save the script and close Vim:
4. Make the script executable:
chmod +x if_else.sh
5. Lastly, run the script multiple times and test for various values:
if elif Statement
elif clause combined with the
if else statement creates multiple conditional checks. The
if elif creates a series of checks with different results. The syntax is:
if <command> then <commands> elif <command> then <commands> else <commands> fi
To create a script using
1. Create a shell file named elif:
2. In the elif.sh file, add the following example code:
echo -n "Please enter a whole number: " read VAR echo Your number is $VAR if [ $VAR -gt 100 ] then echo "It's greater than 100" elif [ $VAR -lt 100 ] then echo "It's less than 100" else echo "It's exactly 100" fi echo Bye!
The example adds an
elif check on line 7 to see if the entered number is less than 100. If the statements in lines 4 and 7 both fail, the program jumps to the else clause.
3. Save and close the file:
4. Make the elif.sh file executable:
chmod +x elif.sh
5. Run the script multiple times and check the behavior for different numbers:
elif clauses to branch out the statement for further detailed checks. For instances where the
elif pattern series grows, the better option is to use a
Nested if Statement
if statements add a branch inside the
if. Specifically, when a command passes the first if check, it goes through a new check to filter the result further. The syntax is:
if <commands> then if <commands> then <commands> fi fi
The nested if is commonly used to search through multi-dimensional arrays. However, try to avoid having more than two or three nested
if statements to reduce program complexity. Rethink the code's logic when the nested
if keeps growing in depth.
Following this tutorial, you should know how to create an
if elif else statement in a bash script and different syntaxes available. Next, check out how to implement the if statement to check if a file or directory exists in bash.