BASH Programming Conditional judgment: Determine whether the prerequisites for subsequent operations are satisfied
Common Types of Judgments:
Integer judgment:
Character Judgment:
File judgment:
$?: Status return value
0: True
1-255: Fake
We can use the status return value as the judging condition, do not need to add ' '
Boolean value:
True and False
Logical operation:
and Operation:&&
Or Operation: | |
Non-op:!
The conditions in bash are judged using if:
Single branch:
if condition; Then
Branch 1;
Fi
Dual Branch:
if condition; Then
Branch 1;
Else
Branch 2;
Fi
Multi-branch:
if condition; Then
Branch 1;
Elif Condition 2; Then
Branch 2;
elif condition 3; Then
Branch 3;
.
.
Else
Branch N;
Fi
Exercise: 1. Let the user specify a file, determine: If the file has a blank line, the number of blank lines is displayed
Nano spaceline.sh
#!/bin/bash
#
Read-p "Enter a file path:" Fliename
If grep "^$" $fileName &>/dev/null; Then do not add ' because we are not using the result of the command but the command state return value
Linescount= ' grep ' ^$ ' $fileName | Wc-l '
echo "$fileName has $linesCount space lines."
Fi
Exercise: 2. Let the user specify a file, determine: If the file has a blank line, the number of blank lines will be displayed, otherwise there will be no blank line output
CP spaceline.sh spaceline2.sh
Nano spaceline2.sh
#!/bin/bash
#
Read-p "Enter a file path:" FileName
If grep "^$" $fileName &>/dev/null; Then
Linescount= ' grep ' ^$ ' $fileName | Wc-l '
echo "$fileName has $linesCount space lines."
Else
echo "$fileName have no space lines"
Fi
17. Self-Learning Linux path: Conditional judgment statement for Bash programming