Many programs impose some logical control processes on the commands in shell scripts.
Structured commands allow you to change the order in which programs are executed. It's not necessarily in sequence.
12.1 using the If-then statement
The following format:
if command
Then
Commands
Fi
The IF statement will allow the command after the IF, if the command's exit code of 0 (which represents success), the command in the then section will be executed. Otherwise, it is not executed.
Example:
#!/bin/bash
# If then test
If PWD
Then
echo "PWD Success"
Fi
# This is the error cmd, no run then commands
If Thiserrorcmd
Then
echo "Com Success"
Fi
echo "This End"
The then section can use more than one command. The bash shell treats these commands as a block, either not executed or all executed.
Example:
#!/bin/bash
# If then test
Testuser=xcy
If grep $testuser/etc/passwd
Then
echo "This is first command"
echo "This is second command"
echo "I can even put in other commands besides Echo:"
Ls-a/home/$testuser/.b*
Fi
12.2 If–then-else Statements
Another set of commands:
if command
Then
Commands
Else
Commands
Fi
You can also follow more than one command after the else.
Example:
#!/bin/bash
# If then test
Testuser=hshsh
If grep $testuser/etc/passwd
Then
echo "This is first command"
echo "I can even put in other commands besides Echo:"
Ls-a/home/$testuser/.b*
Else
echo "Error:this is first command"
echo "Error:not Find User $testuser"
Fi
12.3 Nested IF
Can do this
if command
Then
If Commands
Then
Commands
Else
Commands
Fi
Else
Commands
Fi
This nesting problem is that the code is difficult to read and it's hard to figure out the logic flow . Here's another way to do this:
If Command1
Then
Command1s
Elif Command2
Then
Command2s
Elif Command3
Then
Command3s
Else
Commands
Fi
Example:
#!/bin/bash
# If-then-elif test, can changed TestUser testuser1
Testuser=xcy
Testuser1=xcy
If grep $testuser/etc/passwd
Then
echo "Step0:i can even put in other commands besides Echo:"
Ls-a/home/$testuser/.b*
elif grep $testuser 1/etc/passwd
Then
echo "Step1:i can even put in other commands besides Echo:"
Ls-a/home/$testuser 1/.b*
Else
echo "Not find user $testuser and $testuser 1"
Fi
12.4 Test Command
Test provides a way of testing different conditions in a if-then statement.
If the conditions listed in the test command are true, the test command exits and returns exit status code 0. Then the if then will execute smoothly.
If it does not, the test command exits and returns a non-0 exit status code. The If-then statement will no longer be executed.
The format is as follows:
if test condition
Then
Commands
Fi
When you have a condition, test tests the condition.
(1) If you do not write the condition section, you will exit with a non-0 exit status code.
You can also write this:
Note that there must be spaces on both sides of the condition .
if [condition]
Then
Commands
Fi
Test three types of conditions can be judged:
Numerical comparison
string comparison
File comparison
12.4.1 Numerical comparison
Here is the table for the numeric comparison command: You cannot use floating-point numbers in the test command
N1–eq N2 equals = =
N1–ge n2 equivalent to >=
N1–GT n2 equivalent to >
N1–le n2 equivalent to <=
N1–lt N2 equivalent to <
N1–ne n2 equals! =
12.4.2 string comparison
STR1 = str2 is the same
Str1! = str2 is not the same
STR1 < str2 str1 is less than str2
str1 > STR2 str1 is greater than str2
-N str1 length is not 0
-Z str1 length is 0
1. String equality
Just use =,! = is all right.
2. String order: There are two considerations
(1) The greater than sign must be escaped, otherwise it will be considered a redirect
(2) is greater than and less than the order and sort are used differently.
The uppercase letters in the comparison test are smaller than lowercase letters. The sort command happens
Example:
#!/bin/bash
# Test Command Test
if test
Then
echo "Step1 true"
Else
echo "Step1 false"
Fi
Num=8
if [$num-ge 8] # and you can pick up –le-eq . Wait a whole lot.
Then
echo "Step2 num >= 8"
Else
echo "Step2 num not >= 8"
Fi
Testuser=xcddy
if [$USER! = $testuser]
# if [$USER = $testuser]
Then
echo "step3, user not $testuser"
Else
echo "Step3, User is $testuser"
Fi
Str1=test1 # Small
Str2=test1 # Big
if [$str 1 \> $str 2] # need to be escaped
Then
echo "Step4, $str 1 > $str 2"
Else
echo "Step4, $str 1 <= $str 2"
Fi
str3=
If [-Z $str 3]
#if [-N $str 3]
Then
echo "Step5, $str 3 len is 0"
Else
echo "Step5, $str 3 len is not 0"
Fi
12.4.3 file Comparison
Most powerful, but also the most used form of comparison. Allow testing of the status of files and directories on the Liunx file system
Whether the-D file exists and is a directory
Whether the-e file exists
Whether the-f file exists and is a file
-R file exists and is readable
-s file exists not empty
Whether the-W file exists and is writable
-X file exists and is executable
Whether the-O file exists and is owned by the current user//uppercase O
The-G file exists and the default group is the same as the current user
File1–nt file2 file1 is newer than file2
File1–ot File2 file1 is older than file2
Example:
#!/bin/bash
Jump_dir=testdir
If [-D $jump _dir]
Then
echo "$jump _dir is exist.
CD $jump _dir
Echo-n "now PWD:"
Pwd
Else
echo "$jump _dir is not exist, should create Dir"
mkdir $jump _dir
echo "Change Dir to $jump _dir"
CD $jump _dir
Echo-n "now PWD:"
Pwd
Fi
Test_file=moduleok
If [-e $test _file]
Then
echo "$test _file is exist"
MV Moduleok Running
Sleep 3
MV Running Moduleok
Else
echo "$test _file isn't exist, touch this:"
Touch $test _file
MV Moduleok Running
Sleep 3
MV Running Moduleok
Fi
echo "Check up dir:"
Cd..
Echo-n "now PWD:"
Pwd
Run_test=test2
If [-X $run _test]
Then
echo "You can run the script: $run _test"
./$run _test
Else
echo "You is unable to execute the script: $run _test"
Fi
File1=test1
File2=test5
If [$file 1-nt $file 2]
Then
echo "$file 1 is new, $file 2 was old"
Else
echo "$file 1 is old, $file 2 is new"
Fi
12.5 Qualifying Tests
If-then allows you to combine tests using Boolean logic:
(1) [Condition1] && [condition2]: Use and Boolean operator to combine two conditions
(2) [Condition1] | | [Condition2]: Use or to combine two conditions
Advanced features of 12.6 If-then
Provides two advanced features that you can use in the If-then statement:
(1) Double brackets for mathematical expressions
(2) Two-side brackets for advanced string processing functions
12.6.1 using double brackets
The test command can only use simple arithmetic operations in comparisons.
Allows you to use advanced mathematical expressions in the comparison process. More mathematical symbols are provided.
val++, val--after increase and decrease
++val,--val first increase first minus
! Logical negation
-Position Negation
* * Power operation
<< left displacement >> right displacement
& Bit Boolean and | Bit Boolean or
&& Logic and | | Logical OR
The greater-than sign inside the double brackets does not need to be escaped
12.6.2 using both brackets
Note that not all shells support both brackets.
A regular expression can be defined in a pattern match to match a string
[[Expression]]
Expression uses the standard string comparison used in the test command, but it provides another feature not provided by the test command – pattern matching
Example:
#!/bin/bash
# (()) test
val=10
#val =5
if ((Val * * 2 > 90))
Then
echo "$val ^ 2 > 90"
((val2 = $val * * 2))
echo "Result: $val ^ 2 is $val 2"
Else
echo "$val ^ 2 < 90"
Fi
Str1=xcyhaha
if [[$str 1 = = xcy*]]
Then
echo "str1 = = xcy*, str1 is $str 1"
Else
echo "STR1! = xcy*, str1 is $str 1"
Fi
12.7 Case Command
With the case command, you don't have to write all the elif statements to keep checking the value of the same variable.
The case command takes a list format to examine multiple values for a single variable.
Syntax: Note the two semicolons that follow
Case variable in
Pattern1 | PATTERN2) commands1;;
PATTERN3) commands2;;
*) default commands;;
Esac
The case command compares the specified variable to a different pattern. If the variable and pattern match, then the shell executes the command specified for the change mode.
Multiple pattern modes can be split in a line by a vertical bar operation noon.
* Asterisks capture all values that do not match the known pattern.
The case command provides a clearer way to specify different options for each possible value of a variable.
Example:
#!/bin/bash
var=68
case $ var in
3)
echo "var = 3" ;
4)
echo "var = = 4"
5)
echo "var = = 5"
7|6)
echo "var = = 6|7" ;;
*)
echo "var defaule" Span style= "COLOR: #ff0000" >;
Esac
The Linux command line and Shell script programming encyclopedia 12th use structured commands