Click Back to learn the path of the Linux command line and shell script
12.1-Structured Command If-then
Many programs require some logical process control over the commands in shell scripts. A class of commands will cause the script to skip certain commands depending on the condition. Such commands are often called structured commands (structured command).
1. Basic Structured If-then Statements
Structured commands allow you to change the order in which programs are executed. There are a lot of structured commands in the Bash shell, and the basic Structured command is the If-then statement, and the If-then statement can have two forms
The first type:
1 if command2then3 commands4 fi
The second type:
1 if command;then2 commands3 fi
- The IF statement of the bash Shell runs the command after the IF.
- If the exit status code for the command is 0 (the command runs successfully), the command in the then section is executed.
If the exit status code for the command is a different value, then the command in the then section will not be executed, and the bash shell will continue to execute the next command in the script.
- Then the section can have more than one command, and these commands are treated as a block
If the exit status code for this command is 0 (the command runs successfully), all commands in the then section are executed.
If the exit status code for the command is a different value, then all the commands in the then section will not be executed, and the bash shell will continue to execute the next command in the script.
- The FI statement is used to represent the end of the If-then statement.
Example 1
Example 2
Example 3
Example 4
The If statement line uses the grep command to find out whether a user name is currently being used on the system in the/etc/passwd file. If a user uses that login name, the script displays some textual information and lists the bash files for that user's home directory.
However, if you set the TestUser variable to a user who does not exist on the system, nothing is displayed.
2. If-then-else statements
1 if command2then3 command4else5 Command6 fi
- Commands in the then section are executed when the command in the IF statement returns 0 exit status code
- Commands in the Else section are executed when the command in the IF statement returns a non-0 exit status code
- Else section can contain more than one command
Example 1
Example 2
3. Nesting if
- The bash Shell executes the IF statement sequentially, and only the then part of the first statement that returns exit status code 0 is executed
- In the Elif statement, the Else statement immediately following it belongs to the ELIF code block.
1 ifCommand2 Then3 Command4 elifCommand5 Then6 Command7 elifCommand8 Then9 CommandTen Else One Command AFi
Self-study Linux shell12.1-structured command if-then