How to Use Bash Conditional Statements?
Conditional statements are essential programming constructs that allow scripts to make decisions based on specific conditions. They help control the execution flow by determining which block of commands should run when a condition evaluates to true or false. This decision-making capability makes scripts more dynamic and responsive to different inputs or situations.
In shell scripting, conditional statements use expressions to evaluate conditions before returning a true or false value. These expressions can involve comparisons between numbers, strings, files, or even the exit status of commands. Based on the result, the script executes the appropriate commands, ensuring efficient and logical execution.
This article explores different types of conditional statements, including if, if-else, case, and if/elif/else statements. Each of these constructs serves a unique purpose in handling various conditions, allowing scripts to execute commands based on multiple criteria. Understanding and implementing these statements can significantly enhance the functionality of shell scripts.
Conditional Statements
Shell scripts support multiple types of conditional statements:
- If: Executes a block of commands if a condition is true.
- If-else: Executes one block of commands if a condition is true and an alternative block if the condition is false.
- Case: Tests an expression or variable against multiple patterns and executes the commands associated with the first matching pattern.
- If/elif/else: Sequentially checks multiple conditions and runs the commands matching the first condition that evaluates to true.
Conditional Expressions
Conditional expressions compare values and execute specific commands based on the result. The test command evaluates whether a condition is true or false. The [ ] and [[ ]] operators are used to execute the test command, perform string or arithmetic comparisons, and evaluate specific conditions.
Conditional expressions use different operators depending on the type of condition or operation.
Numeric Operators
Numeric operators compare numeric values and return true or false based on the result. They evaluate arithmetic values as follows:
-eq: Equal to.
-ne: Not equal to.
-gt: Greater than.
-lt: Less than.
-ge: Greater than or equal to.
-le: Less than or equal to.
Example:
[ 1 -eq 1 ]
The above condition checks if 1 is equal to 1.
Logical Operators
Logical operators compare multiple values and return true or false depending on the result. These operators evaluate relationships between two or more conditions:
-a: Logical AND.
-o: Logical OR.
!: Negation.
&&: AND executes the second command if the first succeeds.
||: OR executes the second command if the first fails.
Example:
[ 1 -eq 1 ] && [ 2 -eq 2 ]
Both expressions must be successful to return a zero exit status or a non-zero status in case of failure.
String Operators
String operators compare strings and return true or false based on the condition’s result. They evaluate the character length or the relationship between two or more strings:
=: Equal to.
!=: Not equal to.
<: Less than (lexicographically).
>: Greater than (lexicographically).
Example:
[ “a” != “a” ]
The above test compares the strings and returns true if they are not equal.
File Operators
File operators check file properties such as existence, status, and permissions, returning true or false based on the result. These operators help evaluate the attributes of one or more files:
-e: File exists.
-f: Regular file.
-d: Directory.
-r: File is readable.
-w: File is writable.
-x: File is executable.
Example:
[ -f /etc/hosts ]
The above test returns true if the /etc/hosts file exists.
Exit Status Operators
Exit status operators check whether a command succeeded or failed. The exit status is a numeric value where 0 represents success, and any non-zero value indicates failure.
$?: Stores the exit status of the last executed command.
!: Negates the exit status and returns true if a command fails.
Example:
[ $? -eq 0 ]
The above test returns true if the last command was successful.
Using Conditional Statements
Conditional statements in shell scripts use expressions to evaluate commands or operations before execution. If the condition is true, the associated commands run. If the condition is false, alternative commands are executed or skipped.
If Statement #!/bin/sh if [ 1 -eq 1 ]; then echo "1 is equal to 1" fi If-Else Statement #!/bin/sh if [ 1 -eq 1 ]; then echo "1 is equal to 1" else echo "1 is not equal to 1" fi Case Statement #!/bin/sh var=1 case "$var" in 1) echo "The value is valid" ;; 2) echo "The value does not match" ;; *) echo "Try another value" ;; esac If-Elif-Else Statement #!/bin/sh if [ 1 -eq 1 ]; then echo "1 is equal to 1" elif [ 1 -gt 0 ]; then echo "1 is greater than 0" else echo "1 is not equal to 1" fi
Nested Conditional Statements
Nested conditional statements evaluate a condition multiple times until a match is found. These statements support different types of conditionals at various levels to filter and generate a final result.
Example: #!/bin/sh value=1 case $value in 1) echo "Value is 1" if [ 1 -eq 1 ]; then echo "1 is equal to 1" elif [ 1 -gt 0 ]; then echo "1 is greater than 0" else echo "1 is not equal to 1" fi ;; 2) echo "Value is 2" if [ 2 -eq 2 ]; then echo "2 is equal to 2" elif [ 2 -lt 1 ]; then echo "2 is less than 1" else echo "2 is not less than 1" fi ;; *) echo "Value is neither 1 nor 2" if [ $value -eq 0 ]; then echo "Value is 0" elif [ $value -lt 0 ]; then echo "Value is less than 0" else echo "Value is neither 0 nor less than 0" fi ;; esac
The nested conditional statement above uses a case block to check if the value variable matches a pattern. Within each pattern, a nested if-elif-else block further filters conditions before executing the final command.
Conclusion
Conditional statements allow efficient execution control in shell scripts. They evaluate conditions and execute specific commands based on the result. Additionally, these statements can be combined with loops and functions to create dynamic and interactive shell scripts.