Theory: conditional statement of shell programming-theoretical explanation
Foreword:
Conditional statements are also process control statements, daily life logic.
Conditional test
File test integer test string and logic test
If statement
If single-branch statement if double-branch statement if multi-branch statement 1: conditional test operation 1.1.1 test command tests whether a specific expression is valid. When the condition is true, the return value of the test statement is 0, otherwise it is other values' format 1:test conditional expression 'format 2: [conditional expression]
In format 2, there is at least one space before and after
1.1.2 File test file type and permissions test [operator file or directory] 1.1.3 commonly used test operator-e: test whether a directory or file exists (Exist)-d: test whether it is a directory (Directory)-f: test whether it is a file (File)-r: test whether the current user has permission to read (Read)-w: test whether the current user has the right Write restricted (Write)-x: test whether the current user has permission to execute (eXcute) [root@localhost opt] # touch test.txt [root@localhost opt] # mkdir abc [root@localhost opt] # lsabc rh test.txt wwwroot [root@localhost opt] # test-d / opt/abc/ [root@localhost opt] # echo $? 0 [root@localhost opt] # [d / opt/abc] [root@localhost opt] # echo $? 0 [root@localhost opt] # test -f / opt/abc [root@localhost opt] # echo $? 1 [root@localhost opt] # test-f / opt/test.txt [root@localhost opt] # echo $? 0 [root@localhost opt] # test-f / opt/te.txt [root@localhost opt] # echo $? 1 [root@localhost opt] # [- x / opt/abc] bash: [: missing `]'[root@localhost opt] # [- x / opt/abc] [root@localhost Opt] # ls-al total dosage 16drwxr-xr-x. 5 root root Nov 26 13:51. Dr-xr-xr-x. 17 root root 224 October 23 13:41.. 'drwxr-xr-x. 2 root root 6 November 26 13:51 abcdrwxr-xr-x. 2 root root 6 March 26 2015 rh-rw-r--r--. 1 root root November 26 13:51 test.txt [gsy@localhost opt] $[- w / opt/abc] [gsy@localhost opt] $echo $? 1 [gsy@localhost opt] $[- w / opt/abc] & & echo "yes" [gsy@localhost opt] $echo $? 1 [gsy@localhost opt] $[- r / opt/abc] & & echo "yes" yes [gsy@localhost opt] $echo $? 0 [gsy@localhost opt] $
Echo $? Query whether the previous step is valid. If it is true, it is 0. If not, it is not 0.
[gsy@localhost opt] $[- w / opt/abc] & & echo "yes"
& & and means that it will only be executed correctly if both conditions are true; echo "yes" is obviously correct, that is, if [- w / opt/abc] is established, yes will be output, if not, yes will not be output. This operation can verify whether the operation is valid in a disguised form.
| or ". As long as one is true, the whole is correct. If the first is correct, you will not check the following operations. |
[root@localhost opt] # [- d / opt/abc] | | echo "year" [root@localhost opt] # echo $? 0 [root@localhost opt] # [- d / opt/ab] | | echo "year" year [root@localhost opt] # echo $? 0 [root@localhost opt] # [- d / opt/abc] | | echo "year" [root@localhost opt] # echo $? 01.2.1 Integer value comparison [Integer 1 operator] 2] 1.2.2 commonly used test operators-eq: equal to (Equal)-ne: not equal to (Not Equal)-gt: greater than (Greater Than)-lt: less than (Lesser Than)-le: less than or equal to (Lesser or Equal)-ge: greater than or equal to (Greater or Equal) [root@localhost opt] # [5-gt 3] & & echo "yes" yes [root@localhost opt] # [5 > 3] & echo "yes" yes [root@localhost opt] # [5
< 3 ]&& echo "yes"yes[root@localhost opt]# [ 5 \< 3 ]&& echo "yes"[root@localhost opt]# echo $?1[root@localhost opt]# [ 5 \= 3 ]&& echo "yes"[root@localhost opt]# [ 5 \>3] & & echo "yes" yes [root@localhost opt] # [3\ = 3] & & echo "yes" yes [root@localhost opt] # [3 = = 3] & & echo "yes" yes [root@localhost opt] # [3! = 3] & & echo "yes" [root@localhost opt] # echo $? 1 [root@localhost opt] # [3! = 4] & echo "yes" yes [root@localhost opt] # [3 > = 3] & echo "yes" "bash: [: 3: expecting unary expression [root@localhost opt] # [3 = > 3] & & echo" yes "bash: [: 3: expecting unary expression [root@localhost opt] # [3\ > = 3] & & echo" yes "bash: [: > =: expecting binary expression [root@localhost opt] # [root@localhost opt] # whoroot: 0 2019-11-26 08:16 (: 0) root pts/0 2019-11-26 08:16 (: 0) [root@localhost opt] # [root@localhost opt] # who | wc-L2 [root@localhost opt] # [$(who | wc-l)-lt 5] & & echo "too less" too less [root@localhost opt] # [$(who | wc-l)-ge 2] & & echo "> = 2" > = 2
The command inside $() acts as a reverse prime symbol.
[root@localhost opt] # free-m total used free shared buff/cache availableMem: 1984 686 81 9 1216 1060Swap: 2047 0 2047 [root@localhost opt] # free-m | grep MemMem: 1984 686 81 9 1216 1060 [root@localhost opt] # free-m | grep Mem | awk'{print $1 Mem: 686 81 [root@localhost opt] # free-m | grep Mem | awk'{print $4}'79 [root@localhost opt] # abc=$ (free-m | grep Mem | awk'{print $4}') [root@localhost opt] # echo abcabc [root@localhost opt] # echo $abc77 [root@localhost opt] # [$abc-gt 1024] & echo "yes" [root@localhost opt] # [$abc-gt 50] & & echo "yes" yes1.3.1 string comparison
Format 1:
[string 1 = string 2] [string 1! = string 2]
Format 2:
[- z string] 1.3.2 the commonly used test operator =: the string content is the same! =: the content of the string is different! To express the opposite meaning-z: the string content is empty and the string needs to be marked in double quotation marks 1.3.3 demonstrate [root@localhost opt] # echo $LANGzh_CN.UTF-8 [root@localhost opt] # [$LANG = "zh_CN.UTF-8"] & & echo "yes" yes [root@localhost opt] # [$LANG! = "zh_CN.UTF-8"] & & echo "yes" [root@localhost opt] # echo $? 1 [root@localhost opt] # ["male"! = "male"] & & echo "yes" [root@localhost opt] # ["male" = "male"] & & echo "yes" yes [root@localhost opt] # ["male" = "female"] & & echo "yes" [root@localhost opt] # ["male"! = "female"] & & echo "yes" yes
Inside the brackets are the test statements, which can be compared
Whether to create / opt/share directory: (yes/no) created successfully
Already exists
[root@localhost opt] # ls-al total dosage 16drwxr-xr-x. 5 root root Nov 26 13:51. Dr-xr-xr-x. 17 root root 224 October 23 13:41.. 'drwxr-xr-x. 2 root root 6 November 26 13:51 abcdrwxr-xr-x. 2 root root 6 March 26 2015 rh-rw-r--r--. 1 root root 0 November 26 13:51 test.txt [root@localhost opt] # mv test.txt test.sh [root@localhost opt] # vim test.sh #! / bin/bashread-p "whether to create / opt/share directory: (yes/no)" ack [$ack = "yes"] & & mkdir / opt/shareecho "created successfully" [root@localhost opt] # sh test.sh created / opt/share directory: (yes/no) yes created successfully [ Root@localhost opt] # lsabc share test.sh rh [root@localhost opt] # vim test.sh #! / bin/bashread-p "whether to create / opt/demo directory: (yes/no)" ack [- d / opt/demo] & & echo "/ opt/demo already exists" | | mkdir / opt/demo & & echo "/ opt/demo created successfully" [root@localhost opt ] # whether sh test.sh creates / opt/demo directory: (yes/no) yes/opt/demo created successfully [root@localhost opt] # sh test.sh created / opt/demo directory: (yes/no) yes/opt/demo already exists / opt/demo created successfully
Unary operator:
ITunes 1
ISuppli + is equivalent to i=$i+1, which means that the value is assigned first and then added, that is, it is not re-assigned.
I will add the value first and then assign the value, and then assign the result. At this time, the addition has meaning.
[root@localhost opt] # iposi1 [root@localhost opt] # echo $i1 [root@localhost opt] # i++bash: iComplet: command not found. [root@localhost opt] # iposit + Bash: icommand not found. [root@localhost opt] # expr imanagers + [root@localhost opt] # let icommands + [root@localhost opt] # echo $i2 [root@localhost opt] # let iboxes + [root@localhost opt] # echo $i2 [root@localhost opt] # let icommands + [root@localhost opt] # echo $i3 [root@localhost opt] # let + + I [root@localhost opt] # echo $i4 [root@localhost opt] # let idistributors [root@localhost opt] # echo $i5 [root@localhost opt] # let Syntax error: expected Operand (error symbol is "+") [root@localhost opt] # let ioperations + [root@localhost opt] # echo $i6 [root@localhost opt] # let ioperations 2 [root@localhost opt] # echo $i8 [root@localhost opt] # [root@localhost opt] # I\ * = 2bash: icommand not found. [root@localhost opt] # let I\ * = 2 [root@localhost opt] # echo $i16 [root@localhost opt] # let iAction2 [root@localhost opt] # echo $i8 [root@localhost opt] # let I% command 2 [root@localhost opt] # echo $i0 [root@localhost opt] # echo $i0 [root@localhost opt] #
Binary operator
A+b=c
Ternary operator
Condition & & result 1 | result 2
The condition holds the execution result 1, but the execution result 2 is not established.
1.4.1 Logic Test
Format 1:
[expression 1] operator [expression 2]
Format 2:
Command 1 operator Command 2 1.4.2 commonly used test operators-an or &: logic and, "and" means-o or |: logic or, or! Logical no It means [root@localhost opt] # [- d / etc] & echo "you can open / etc this diretory" you can open / etc this diretory [root@localhost opt] # [- d / etc] | | [- d / home] & & echo "ok" ok [root@localhost opt] # [- r / etc] | | [- d / home] & & echo "ok" ok [root@localhost opt] # [ -r / etc] | | [- r / home] & & echo "ok" ok [root@localhost opt] # [- f / etc] | | [- f / home] & & echo "ok" [root@localhost opt] # echo $? 1 [root@localhost opt] # [!-f / etc] | | [- f / home] & & echo "ok" ok II: the structure of if sentence 2.1 single branch structure
Judging when fi ends, exit 0 exits normally and exit 1 exits abnormally.
2.2 double-branched structure
2.3 Multi-branch structure
3: if statement application example 3.1 single branch if statement to determine the mount point directory, if it does not exist, it will be created automatically
[root@localhost opt] # vim test02. Sh test02.sh sh test02.sh opt/demo02 [root@localhost opt] # ls [root@localhost opt] # lsabc share test.sh rh demo02 [root@localhost opt] # vim created successfully [root@localhost opt] # ls [root@localhost opt] # lsabc share test.sh rh demo02 [root@localhost opt] # vim Test02.shroomroombinhampash if = "/ opt/demo02" if [!-d $dir] thenmkdir-p $direcho "$dir created successfully" elseecho "$dir already exists" I [root @ localhost opt] # sh test02.sh / opt/demo02 already exists # # 3.2 two-branch if statement-determine whether the target host is alive or not Display the test result-the number of packets sent by ping-c-I interval time, wait for the location variable ip address of 3s $1, and output the result to null. If the previous result is equal to 0, then output up. Else will down! [] (https://s1.51cto.com/images/blog/201911/26/a02e04631aec4534762c49c2f54bbe34.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90, Type_ZmFuZ3poZW5naGVpdGk=) Please enter the IP address: ```shell [root @ localhost opt] # vim test02.addr-p "enter the IP address:" addrping-c 3-I 0.2-W 3$ addr & > / dev/nullif [$?-shell0] then echo "$addr is up" $addr is down "fi [root@localhost opt] # sh test02.sh please enter the IP address: 192.168.139.132192.168.139.132 is up [root@ Localhost opt] # sh test02.sh enter IP address: 139.168.139.133139.168.139.133 is down [root@localhost opt] # 3.3 Multi-branch statement
Elif, otherwise if
Exit 1 abnormal exit
[root@localhost opt] # vim fenshu.shemake binbinBash read-p "Please enter your score" scoreif [$score-lt 0] then echo "you are hopeless" elif [$score-gt 100] then echo "Don't dream" elif [$score-ge 85] then echo "excellent" elif [$score-lt 70] then echo "fail, work hard ah teenager" else echo "pass, don't stop there, keep trying!" Fi~ [root@localhost opt] # sh fenshu.sh Please enter your score-9 you are hopeless [root@localhost opt] # sh fenshu.sh Please enter your score 101.Don 't dream [root@localhost opt] # sh fenshu.sh Please enter your score 90 excellent [root@localhost opt] # sh fenshu.sh Please enter your score 60 fail, and work hard, boy.
Summary: grammar file tests, integer value comparisons, string comparisons, logic tests illustrating the grammar single-branch, double-branch and multi-branch of if conditional statements for conditional test operations
A simple calculator
#! / bin/bashread-p "Please enter an integer:" numb1read-p "Please select the operation you want Option: add (+) subtract (-) multiply (x) divide (%) "yunsuanread-p" Please enter the second integer: "numb2if [" $yunsuan "=" + "] then expr= `expr $numb1 + $numb2`echo" $numb1 + $numb2 = $expr "elif [" $yunsuan "="-"] then expr= `expr $numb1-$numb2` echo" $numb1-$numb2 = $expr "elif [" $yunsuan "=" x "] then expr= `expr $numb1\ * $numb2` echo" $numb1 X $numb2 = $expr "elif [" $yunsuan "=" / "] then expr= `expr $numb1 / $numb2` echo" $numb1 / $numb2 = $expr "else expr= `expr $numb1% $numb2` echo" $numb1% $numb2 = $expr "fi~ ~ [root@localhost opt] # sh jisuanqi.sh Please enter an integer: 10 Please select the operation you want Option: add (+) subtract (-) multiply (x) divide (/) take the remainder (%) + enter the second integer: 810 + 8 = 18 [root@localhost opt] # vim jisuanqi.sh [root@localhost opt] # sh jisuanqi.sh Please enter an integer: 10 Please select the operation you want Option: add (+) minus (-) multiply (x) divide (/) take the remainder (%)-Please enter the second integer: 510-5 = 5 [root@localhost opt] # sh jisuanqi.sh Please enter an integer: 10 Please select the operation you want Option: add (+) minus (-) multiply (x) divide (/) take the remainder (%) x enter the second integer: 2 [root@localhost opt] # sh jisuanqi.sh Please enter an integer: 17 Please select the operation you want Options: add (+) subtract (x) multiply (x) divide (/) take the remainder (%) Please enter the second integer: 417% 4 = 1 [root@localhost opt] # sh jisuanqi.sh Please enter an integer: 10 Please select the operation you want; options: add (+) minus (-) multiply (x) divide (/) take the remainder (%) / enter the second integer: 510 / 5 = 2
Assignment: track and field final list elimination list name gender achievement
[root@localhost opt] # vim tianjingsai.sh 1 #! / bin/bash 2 fnan=/opt/nanzizujuesaimingdan 3 fnv=/opt/nvzizujuesaimingdan 4 ftao=/opt/taotaimingdan 5 if [!-f $fnan] & & [!-f $fnv] & & [!-f $ftao] 6 then 7 touch $fnan $fnv $tao 8 fi 9 read-p "Please enter (format: name, gender score):" xingming xingbie chengji 10 if [$chengji-lt 0] 11 then 12 echo "? What are you losing? "13 exit 1 14 elif [$chengji-gt 0] & & [$chengji-lt 10] 15 then 16 echo" your performance is excellent and you can enter the finals in 10 seconds "17 if [$xingbie =" nan "] 18 then 19 echo" $xingming $xingbie $chengji "> > / opt/nanzizujuesaimingdan 20 else 21 echo" $xingming $xingbie $chengji "> / opt/nvzizujuesaimingdan 22 fi 23 else 24 echo" $xingming $xingbie $chengji "> > / opt/taotaimingdan 25 echo. Next time it will be you. "26 27 fi~ [root@localhost opt] # sh tianjingsai.sh Please enter (format: name gender score): gsy nan 1 your score is excellent and you can enter the finals within 10 seconds [root@localhost opt] # sh tianjingsai.sh Please enter (format: name gender score): zzz nv 6 your score is excellent You can enter the final [root@localhost opt] # sh tianjingsai.sh in 10 seconds. Please enter (format: name and gender score): aaa nan-6 minutes? What are you losing? [root@localhost opt] # sh tianjingsai.sh Please enter (format: name gender score): aaa nan 14 try harder Next time it's you [root@localhost opt] # lsfenshu.sh nvzizujuesaimingdan taotaimingdan test.sh wwwrootnanzizujuesaimingdan rh test02.sh tianjingsai.sh [root@localhost opt] # cat nvzizujuesaimingdan zzz nv 6 [root@localhost opt] # cat nanzizujuesaimingdan gsy nan 1 [root@localhost opt] # cat taotaimingdan gsy nan 0.5aaa nan 14