当前位置:网站首页>Conditional test, if and case conditional test statements of shell script
Conditional test, if and case conditional test statements of shell script
2022-06-29 05:41:00 【One color stocks plummeted】
List of articles
Preface
One 、 Conditions for testing
Test whether a specific expression holds , When conditions hold , The return value of the test statement is 0, Otherwise, other values
Format :
test Conditional expression
or
[ Conditional expression ] ( Spaces are required on both sides of the conditional expression , And this method is more commonly used )
File test
File testing refers to testing based on a given path name , Determine whether the corresponding file or directory , Or judge whether the file is readable 、 Can write 、 Executable, etc .
Common options for file testing 
After performing the conditional test operation , Through predefined variables " $ ? " You can get the return status value of the test command , So as to judge whether the condition is true . for example , Do the following to test the directory /media/ Whether there is , If the return value " $ ? " by 0, Indicates that this directory exists , Otherwise, it means that it does not exist or although it exists, it is not a directory
[[email protected] ~]# test -d /media/;echo $?
0 ### The return value is 0
Example :
[[email protected] ~]# test -d /etc/;echo $? ### Test whether it's a directory
0 ### Return value 0 Is a directory
[[email protected] ~]# test -e /etc/abc;echo $? ### Test whether the directory or file exists
1 ### Return value 1 There is no directory file
[[email protected] ~]# test -f /etc/yum.conf ;echo $? ### Whether the test is a file
0 ### Return value 0 It's a document
[[email protected] ~]# test -r /etc/yum.conf ;echo $? ### Test whether the current user has permission to read
0 ### Return value 0 The current user has read permission
[[email protected] ~]# test -w /etc/yum.conf ;echo $? ### Test whether the current user has permission to write
0 ### Return value 0 The current user has write permission
[[email protected] ~]# test -x /etc/yum.conf ;echo $? ### Test whether the current user has permission to execute
1 ### Return value 1 The current user does not have permission to execute
have access to “&&” and “echo” Together with
[[email protected] ~]# test -d /etc/ && echo "yes"
yes
Integer comparison
Integer value comparison refers to the comparison between two given integer values , Judge the relationship between the first number and the second number , If it is greater than 、 be equal to 、 Less than the second number
Format :
[ Integers 1 The operator Integers 2 ]
Common test operators
The operator meaning
-eq be equal to (Equal)
-ne It's not equal to (Not Equal)
-lt Less than (Leser Than)
-gt Greater than (Greater Than)
-le Less than or equal to (Lesser or Equal)
-ge Greater than or equal to (Greater or Equal)
Query whether the number of files in the current directory is greater than 10, If it is greater than , Then give a hint
[[email protected] ~]# ls | wc -l
11
[[email protected] ~]# test ` ls | wc -l ` -gt 10 && echo " Number of files greater than 10"
Number of files greater than 10
Check whether the system memory is lower than 1300M, If it is lower than, it will prompt
[[email protected] ~]# free -m
total used free shared buff/cache available
Mem: 3771 724 1244 17 1801 2712
Swap: 2999 0 2999
[[email protected] ~]# free -m | grep "Mem"
Mem: 3771 724 1244 17 1801 2712
[[email protected] ~]# free -m | grep "Mem" | awk '{print $4}'
1244
[[email protected] ~]# free=`free -m | grep "Mem" | awk '{print $4}'`
[[email protected] ~]# echo $free
1244
[[email protected] ~]# test `echo $free` -lt 1300 && echo " Out of memory 1300M"
Out of memory 1300M
String comparison
String comparisons are often used to check user input 、 Whether the system environment meets the conditions , In providing interactive operation shell Script , It can also be used to judge whether the position parameters entered by the user meet the requirements
Format :
[ character string 1 = character string 2 ] ### Judge whether it is equal
[ character string 1 != character string 2 ] ### Judge whether it is not equal
[ -z character string ] ### Determine whether the string content is empty
Common test operators
The operator meaning
= String content is the same
!= String content is different ,! The sign means the opposite
-z The string content is empty
Judge whether the current system language environment is “us.en”, If not, it will prompt
[[email protected] ~]# echo $LANG
zh_CN.UTF-8
[[email protected] ~]# test ` echo $LANG `="us.en" && echo The current language is not us.en, The current language is `echo $LANG`
The current language is not us.en, The current language is zh_CN.UTF-8
Logic test
Logical testing refers to judging the dependency between two or more conditions . When the system task depends on several different conditions , According to whether these conditions are established at the same time or as long as one of them is established , There needs to be a testing process
Format :
[ expression 1 ] The operator [ expression 2 ]
command 1 The operator command 2
Common test operators
The operator meaning
-a or && Logic and , And it means
-o or ▕▕ Logic or , Or it means
! Logical not
[[email protected] ~]# [ -d /etc ] && [ -r /etc ] && echo "you can open it "
you can open it
[[email protected] ~]# [ -d /etc ] || [ -d /home ] && echo " ok "
ok
if sentence
Single branch structure
For single branch selection structure , Only in " Conditions established " The corresponding code will be executed , Otherwise, nothing will be done
Format :
if [ Conditional judgment ]; than
When the condition is right , Execute one or more commands
fi
Using a single branch if Sentence judgment test Does the file exist
[[email protected] ~]# if test -e /etc ; then echo Directory exists ; fi
Directory exists
[[email protected] ~]# if test -e /etc/yum.conf ; then echo File exists ; fi
File exists
example 2.
Determine the mount point , If it doesn't exist, it will be created automatically
#!/bin/bash
MOUNT_DIR="/media/cdrom/ "
if [ ! -d $MOUNT_DIR ];
then
mkdir -p $MOUNT_DIF
fi
example 3
Determine whether the end of the input is .sh
#!/bin/bash
read -p " Please enter filename :" file
if [[$file == *.sh ]] ;then
echo " This is a shell Script "
fi
Two branch structure
Double branch if The statement is only on a single branch basis for " Conditions not established " To perform another operation , instead of " Sit idly by " Without doing anything
if [ Conditional judgment ]; then
When the condition is right , You can execute one or more commands
else
When the conditional judgment doesn't hold , You can execute one or more commands
fi
In the judgment of the same data , If the data requires two different judgments , We need two branches if Statement :
Example :
Judge whether the current login user is an administrator
[[email protected] ~]# vim a.sh
#!/bin/bash
if [ $UID -eq 0 ];then
echo " The current login user is administrator root"
else
echo " The current login user is not an administrator "
fi
[[email protected] ~]# sh a.sh
The current login user is administrator root
Check that the directory exists
[[email protected] ~]# vim b.sh
#!/bin/bash
read -p " Check that the directory exists , Please enter the directory :" aaa
if ls $aaa &> /dev/null
then
echo " Directory exists "
else
echo " Please enter the correct path "
fi
[[email protected] ~]# sh b.sh
Check that the directory exists , Please enter the directory :/etc
Directory exists
Multi branch structure
And single branch 、 Double branch if Statement than , Multiple branches if The structure of the statement can perform different operations according to multiple mutually exclusive conditions
if [ Conditional judgment ]; then
When the condition is right , You can execute one or more commands
elif [ Conditional judgment 2 ]; then
When the condition is right , You can execute one or more commands
else
When none of the above conditions are true , You can execute one or more commands
fi
Example
Excellent students are distinguished according to the test scores entered 、 qualified 、 Three unqualified grades
[[email protected] ~]# vim c.sh
#!/bin/bash
read -p " Please enter your score (0-100) : " GE
if [ $GE -ge 85 ] && [ $GE -le 100 ]
then
echo "$GE branch , good !"
elif [ $GE -ge 70 ] && [ $GE -le 84 ]
then
echo "$GE branch , qualified !"
else
echo "$GE branch , unqualified !"
fi
[[email protected] ~]# sh c.sh
Please enter your score (0-100) : 99
99 branch , good !
[[email protected] ~]# sh c.sh
Please enter your score (0-100) : 79
79 branch , qualified !
[[email protected] ~]# sh c.sh
Please enter your score (0-100) : 59
59 branch , unqualified !
Determine the file category
[[email protected] ~]# vim d.sh
#!/bin/bash
read -p " Enter the file to identify :" name
if [ -d $name ] ;then
echo " This is a directory "
elif [ -f $name ];then
echo " This is a document "
elif [ -b $name ];then
echo" This is a device file "
else
echo " Unable to determine file type "
fi
[[email protected] ~]# sh d.sh
Enter the file to identify :/etc
This is a directory
[[email protected] ~]# sh d.sh
Enter the file to identify :/etc/yum.conf
This is a document
[[email protected] ~]# sh d.sh
Enter the file to identify :root
Unable to determine file type
nesting if sentence
example 1. Judge httpd Did the service start
Judge whether to start
If you start ------ Output started
If it doesn't start ------ Determine whether to install ------ If installed ------ start-up
If not installed ------ install ------ If the installation is successful ------ start-up
If the installation is not successful ------ Report errors
[email protected] ~]# vim e.sh
#!/bin/bash
ps -aux | grep httpd | grep -v grep
if [ $? -ne 0 ];then
if [ "$(rpm -q httpd)" == " Package not installed httpd" ];then
yum install httpd -y
systemctl start httpd
else
systemctl start httpd
fi
else
echo "httpd Service started "
fi
```c
[[email protected] ~]# sh e.sh
root 11870 0.6 0.1 224072 5044 ? Ss 15:05 0:00 /usr/sbin/httpd -DFOREGROUND
apache 11874 0.0 0.0 226156 3112 ? S 15:05 0:00 /usr/sbin/httpd -DFOREGROUND
apache 11875 0.0 0.0 226156 3112 ? S 15:05 0:00 /usr/sbin/httpd -DFOREGROUND
apache 11876 0.0 0.0 226156 3112 ? S 15:05 0:00 /usr/sbin/httpd -DFOREGROUND
apache 11877 0.0 0.0 226156 3112 ? S 15:05 0:00 /usr/sbin/httpd -DFOREGROUND
apache 11878 0.0 0.0 226156 3112 ? S 15:05 0:00 /usr/sbin/httpd -DFOREGROUND
httpd Service started
case sentence
case Statement can make the structure of the script program clearer 、 distinct , Commonly used for service startup 、 restart 、 Stopped script , Some services do not provide such control scripts , Need to use case Statement writing
case Statement is mainly applicable to the following situations : There are many values for a variable , You need to execute different command sequences for each value . This is the case with multi - branched if The sentences are very similar , It's just if Statements need to judge multiple different conditions , and case The statement just judges the different values of a variable
Format :
case Variable name in
Pattern 1)
Command sequence
;;
Pattern 2)
Procedures section
;;
*)
Other program execution segments that do not contain the contents of the first variable and the second variable
Default segment
;;
esac
Be careful :
case The line must begin with a word “in”, The first mock exam is a single bracket. ")" end
Double a semicolon ";;" Indicates the end of the command sequence
In pattern string , You can use square brackets to indicate a continuous range , Such as "[0-9]"; You can also use vertical bars | Represents or , such as a|b
final ) Represents the default mode , Where is equivalent to wildcard
Example
Check the character type entered by the user
[[email protected] ~]# vim f.sh
#!/bin/bas
read -p " Please enter a character , And press Enter Key confirmation :" KEY
case "$KEY" in
[a-z] | [A-Z])
echo " You're typing in letters "
;;
[0-9])
echo " You're typing in numbers "
;;
*)
echo " What you enter is a space or special character "
esac
[[email protected] ~]# sh f.sh k
Please enter a character , And press Enter Key confirmation :k
You're typing in letters
[[email protected] ~]# sh f.sh
Please enter a character , And press Enter Key confirmation :5
You're typing in numbers
[[email protected] ~]# sh f.sh
Please enter a character , And press Enter Key confirmation :
What you enter is a space or special character
Example 2
[[email protected] ~]# vim g.sh
#!/bin/bash
read -p " Please enter your score :" score
case $score in
100 )
echo " Full marks !"
;;
9[0-9])
echo "$score branch "
;;
[78][0-9])
echo "$score branch "
;;
6[0-9])
echo "$score branch "
;;
[0-9]|[1-5][0-9])
echo "$score branch "
;;
*)
echo " Incorrect input !"
esac
[[email protected] ~]# sh g.sh
Please enter your score :100
Full marks !!
[[email protected] ~]# sh g.sh
Please enter your score :91
91 branch
[[email protected] ~]# sh g.sh
Please enter your score :78
78 branch
[[email protected] ~]# sh g.sh
Please enter your score :65
65 branch
[[email protected] ~]# sh g.sh
Please enter your score :50
50 branch
[[email protected] ~]# sh g.sh
Please enter your score :1000
Incorrect input !
summary
- The syntax of conditional testing : File test 、 Integer comparison 、 String comparison 、 Logic test .
- if The syntax of conditional statements : Single branch 、 Double branch 、 Multiple branches .
- case The syntax of a multi branch statement
边栏推荐
- Difference between parametric continuity and geometric continuity
- 5,10-di (4-aminophenyl) - 15,20-diphenylporphyrin (cis-dadph2) /5,15-di (4-aminophenyl) - 10,20-diphenylporphyrin (trans-dadph2) / (tri-apph2) supplied by Qiyue
- Research Report on the new energy industry of recommended power equipment in 2022 industry development prospect market investment analysis (the attachment is a link to the network disk, and the report
- The translation of those exquisite lines in the eighth season of the big bang
- Modularization and modular specification commonjs
- Est - ce que l'ouverture d'un compte de titres est sécurisée? Y a - t - il un danger?
- C language uses printf to print love, Mars strikes the earth, etc., which are constantly updated
- Design risc-v processor from scratch -- data adventure of five stage pipeline
- STI, one controller
- 2022-2028 global and Chinese industrial electronic detonator Market Status and future development trend
猜你喜欢

Research Report on the recommended lithography industry in 2022 industry development prospect market investment analysis (the attachment is a link to the network disk, and the report is continuously u

2022 recommended cloud computing industry research report investment strategy industry development prospect market analysis (the attachment is a link to the online disk, and the report is continuously

HTTP Caching Protocol practice

Top ten Devops best practices worthy of attention in 2022

The first commercial spacewalk of mankind is finalized! Musk SpaceX announced a new round of space travel plan, and the American rich became repeat customers

2022 recommended REITs Industry Research Report investment strategy industry development prospect market analysis (the attachment is a link to the online disk, and the report is continuously updated)

5,10-di (4-aminophenyl) - 15,20-diphenylporphyrin (cis-dadph2) /5,15-di (4-aminophenyl) - 10,20-diphenylporphyrin (trans-dadph2) / (tri-apph2) supplied by Qiyue

Tcapulusdb Jun · industry news collection (VI)

Research Report on the new energy industry of recommended power equipment in 2022 industry development prospect market investment analysis (the attachment is a link to the network disk, and the report

2022 recommended prefabricated construction industry research report industry development prospect market analysis white paper (the attachment is a link to the network disk, and the report is continuo
随机推荐
data management plan
Accelerate the global cloud native layout, kyligence intelligent data cloud officially supports Google cloud
CCTV revealed that xumengtao won the black Technology: there was a virtual coach???
patent filter
Software architecture final review summary
Distributed transaction Seata
51 single chip microcomputer learning notes 7 -- Ultrasonic Ranging
Annual inventory review of Alibaba cloud's observable practices in 2021
Structure training camp module II operation
patent filter
3 frequently tested SQL data analysis questions (including data and code)
i-Teams W3: How to build a sound-bottling business
2,5-di (3,4-dicarboxyphenoxy) - 4 '- phenylethynylbiphenyldianhydride (pephqda) / Qiyue custom supply porphyrin modified amphiphilic block copolymer peg113-pcl46-porphyrin
Microsoft Pinyin IME personal preferences
The first in China! CICA technology database antdb appears at the performance test tool conference of China Academy of communications technology
STI, one controller
Blip: conduct multimodal pre training with cleaner and more diverse data, and the performance exceeds clip! Open source code
Collection of common terms used in satellite navigation
DANGER! V** caught climbing over the wall!
Slot