In a shell script,if-then
Statements are one of the most basic logical control structures, used to execute different code blocks according to conditions. The following is aboutif-then
The basic structure, syntax and some examples of the statement.
Basic syntax
if Conditional expression; then # Commands executed when the conditional expression is true Order1 Order2 ... else # Commands executed when the conditional expression is false OrderA OrderB ... fi
Detailed explanation
-
if
Keywords:-
if
Keywords start a conditional judgment.
-
-
Conditional expression:
- A conditional expression can be a relational expression, a logical expression, or any other Boolean expression.
- Conditional expressions are usually placed in parentheses
()
, to improve readability and avoid parsing errors.
-
then
Keywords:-
then
The keyword indicates the beginning of the code block after the conditional expression.
-
-
Command block:
- When the conditional expression is true, execute
then
The command block behind.
- When the conditional expression is true, execute
-
else
Keywords (optional):-
else
Keywords represent code blocks executed when the conditional expression is false. -
else
Blocks are optional and can be omitted if there is no need to deal with cases where the conditions are false.
-
-
fi
Keywords:-
fi
Keyword ends the wholeif
Sentence.
-
Example
Example 1: Basic usage
#!/bin/bash # Get user inputread -p "Please enter a number: " num # Determine whether the number is greater than 10if [ "$num" -gt 10 ]; then echo "Numbers greater than 10" else echo "The number is less than or equal to 10" fi
Example 2: Using logical operators
#!/bin/bash # Get user inputread -p "Please enter a number: " num # Determine whether the number is between 1 and 10if [ "$num" -ge 1 ] && [ "$num" -le 10 ]; then echo "The number is between 1 and 10" else echo "The number is not between 1 and 10" fi
Example 3: Nested if-then statements
#!/bin/bash # Get user inputread -p "Please enter a number: " num # Determine whether the number is a positive, negative or zeroif [ "$num" -gt 0 ]; then echo "The number is a positive number" elif [ "$num" -lt 0 ]; then echo "The number is a negative number" else echo "The number is zero" fi
Conditional expression
1. Numerical comparison
# Compare values[ "$num" -eq 10 ] # equals[ "$num" -ne 10 ] # Not equal to[ "$num" -gt 10 ] # Greater than[ "$num" -lt 10 ] # Small[ "$num" -ge 10 ] # greater than or equal to[ "$num" -le 10 ] # Less than or equal to
2. String comparison
# Compare strings[ "$str" = "hello" ] # equals[ "$str" != "hello" ] # Not equal to[ "$str" \< "hello" ] # Dictionary order is smaller than[ "$str" \> "hello" ] # Dictionary order is greater than
3. File testing
# Test file properties[ -f "$file" ] # is a normal file[ -d "$file" ] # Yes directory[ -r "$file" ] # Readable[ -w "$file" ] # Writable[ -x "$file" ] # Executable[ -s "$file" ] # File not empty
Example 4: File Testing
#!/bin/bash # Get the file name entered by the userread -p "Please enter a file name: " filename # Test whether the file exists and is a normal fileif [ -f "$filename" ]; then echo "The file exists and is a normal file" else echo "The file does not exist or is not a normal file" fi
The bash shell also provides 3 advanced features that can be used in if-then statements.
- Execute single brackets of commands in a subshell.
- Double brackets for mathematical expressions.
- Two-side brackets for advanced string processing capabilities.
Each feature will be described in detail next.
Use single brackets
Single brackets allow the use of subshells in if statements. The format of the test command in single bracket form is as follows:
(command)
Before the bash shell executes command, a child shell is created first and then the command is executed. If the command ends successfully, the exit status code will be set to 0 and the command in the then part will be executed. If the exit status code of the command is not 0, then the command in the then part is not executed. Let’s take a look at an example of using a subshell for testing:
$ cat #!/bin/bash # Testing a single parentheses condition # echo $BASH_SUBSHELL # if (echo $BASH_SUBSHELL) then echo "The subshell command operated successfully." # else echo "The subshell command was NOT successful." # fi $ $ ./ 01 The subshell command operated successfully.
When the script executes the echo $BASH_SUBSHELL command for the first time (before the if statement), it is done in the current shell. This command will output 0, indicating that no subshell is used. In the if statement, the script executes the echo $BASH_SUBSHELL command in the subshell, which outputs 1, indicating that the subshell is used. The subshell operation ends successfully, and then executes the commands in the then part.
Warning When you use a process list in an if test statement, unexpected results may occur. Even if all other commands in the process list fail, the subshell will still set the exit status code to 0, and the commands in the then part will be executed.
Make a slight modification to the script and see an example of failure in execution in a subshell:
$ cat #!/bin/bash # Testing a single parentheses condition # echo $BASH_SUBSHELL # if (cat /etc/PASSWORD) then echo "The subshell command operated successfully." # else echo "The subshell command was NOT successful." # fi $ $ ./ cat: /etc/PASSWORD: NO such file or directory The subshell command was NOT successful.
Because the command in the subshell specifies the wrong file name, the exit status code is set to non-0. Next, execute the else part command.
Use double brackets
The double-bracket command allows the use of advanced mathematical expressions during comparison. The test command can only use simple arithmetic operations when comparing. The double-bracket command provides more mathematical symbols that are no strangers to programmers who have experience in other programming languages. The format of the double-bracket command is as follows:
((expression))
The expression can be any mathematical assignment or comparison expression. In addition to the standard mathematical operators used by the test command, the table also lists other operators available in double brackets.
Double bracket command symbol
symbol | describe |
---|---|
val++ | Later |
val-- | Reduce later |
++val | Add first |
--val | Reduce first |
! | Logical inverse |
~ | Reverse position |
** | Power operation |
<< | Left displacement |
>> | Right displacement |
& | Bitboolean AND |
| | Bitboolean OR |
&& | Logical AND |
|| | Logical OR |
The double-bracket command can be used in if statements or assign values in ordinary commands in scripts:
$ cat #!/bin/bash # Testing a double parentheses command # val1=10 # if (( $val1 ** 2 > 90 )) then (( val2 = $val1 ** 2 )) echo "The square of $val1 is $val2," echo "which is greater than 90." # fi $ $ ./ The square of 10 is 100, which is greater than 90.
Note that the greater than the expression in double brackets does not need to be escaped. This is another manifestation of the superiority of the double-bracket command.
Use both brackets
The two-sided bracket command provides advanced features for string comparisons. The format of both brackets is as follows:
[[ expression ]]
Expression can be compared using standard strings in the test command. In addition, it also provides another feature that the test command does not have - pattern matching.
Note The brackets work well in the bash shell. Be careful, though, not all shells support both brackets.
When doing pattern matching, you can define wildcards or regular expressions to match strings:
$ cat #!/bin/bash # Using double brackets for pattern matching # # if [[ $BASH_VERSION == 5.* ]] then echo "You are using the Bash Shell version 5 series." fi $ $ ./ You are using the Bash Shell version 5 series.
The above script uses a double equal sign (==). A double equal sign treats the string (5.*) on the right as a pattern and applies a pattern matching rule. The bracket commands on both sides will match the $BASH_VERSION environment variable to see if it starts with string 5. If so, the test passes and the shell will execute the commands in the then part.
Summarize
if-then
Statements are one of the most basic logical control structures in Shell scripts, used to execute different code blocks according to conditions. Combining different conditional expressions and logical operators can achieve complex logical judgments.
This is the end of this article about the advanced use of if-then in shell. For more related shell if-then content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!