当前位置:网站首页>Conditional test, if, case conditional test statements of shell script
Conditional test, if, case conditional test statements of shell script
2022-07-04 01:07:00 【Wozkid】
One 、 Conditions for testing
1.1 test command
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 )
- 1.
- 2.
- 3.
- 4.
1.2 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
Common test operators meaning
-d Test whether it's a directory (directory)
-e Test whether the directory or file exists (Exist)
-f Whether the test is a file (File)
-r Test whether the current user has permission to read (Read)
-w Test whether the current user has permission to write (Write)
-x Test whether the current user has permission to execute (eXcute)
-L Test whether it is a soft connection file
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
- 1.
- 2.
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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
1.3 Integer comparison
Format :
[ Integers 1 The operator Integers 2 ]
- 1.
- 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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
1.4 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
- 1.
- 2.
- 3.
- 4.
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
- 1.
- 2.
- 3.
- 4.
- 5.
1.5 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
- 1.
- 2.
- 3.
- 4.
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
- 1.
- 2.
- 3.
- 4.
Two 、if sentence
2.1 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
- 1.
- 2.
- 3.
- 4.
# 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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
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
- 1.
- 2.
- 3.
- 4.
- 5.
2.2 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
- 1.
- 2.
- 3.
- 4.
- 5.
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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
2.3 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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
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 !
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
2.4 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
[[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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
3、 ... and 、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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
Example 2
[[email protected] ~]# vim g.sh
#!/bin/bash
read -p " Please enter your score :" score
case $score in
100 )
echo " Xiuer !"
;;
9[0-9])
echo "$score branch , copy 10 All over !"
;;
[78][0-9])
echo "$score branch , copy 20 All over !"
;;
6[0-9])
echo "$score branch , copy 30 All over !"
;;
[0-9]|[1-5][0-9])
echo "$score branch , Copy all 30 All over !"
;;
*)
echo " Incorrect input !"
esac
[[email protected] ~]# sh g.sh
Please enter your score :100
Xiuer !
[[email protected] ~]# sh g.sh
Please enter your score :91
91 branch , copy 10 All over !
[[email protected] ~]# sh g.sh
Please enter your score :78
78 branch , copy 20 All over !
[[email protected] ~]# sh g.sh
Please enter your score :65
65 branch , copy 30 All over !
[[email protected] ~]# sh g.sh
Please enter your score :50
50 branch , Copy all 30 All over !
[[email protected] ~]# sh g.sh
Please enter your score :1000
Incorrect input !
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
Four 、 summary
1. The syntax of conditional testing : File test 、 Integer comparison 、 String comparison 、 Logic test .
2.if The syntax of conditional statements : Single branch 、 Double branch 、 Multiple branches .
3.case The syntax of a multi branch statement
边栏推荐
- 7.1 学习内容
- A malware detection method for checking PLC system using satisfiability modulus theoretical model
- Five high-frequency questions were selected from the 200 questions raised by 3000 test engineers
- [common error] custom IP instantiation error
- Avoid playing with super high conversion rate in material minefields
- What insurance products should be bought for the elderly?
- Sequence list and linked list
- Force deduction solution summary 1189- maximum number of "balloons"
- CLP information - how does the digital transformation of credit business change from star to finger?
- be based on. NETCORE development blog project starblog - (14) realize theme switching function
猜你喜欢
What is the GPM scheduler for go?
OS interrupt mechanism and interrupt handler
功能:求5行5列矩阵的主、副对角线上元素之和。注意, 两条对角线相交的元素只加一次。例如:主函数中给出的矩阵的两条对角线的和为45。
Pratique technique | analyse et solution des défaillances en ligne (Partie 1)
HackTheBox-baby breaking grad
Avoid playing with super high conversion rate in material minefields
A-Frame虚拟现实开发入门
功能:求出菲波那契数列的前一项与后一项之比的极限的 近似值。例如:当误差为0.0001时,函数值为0.618056。
老姜的特点
Function: find the sum of the elements on the main and sub diagonal of the matrix with 5 rows and 5 columns. Note that the elements where the two diagonals intersect are added only once. For example,
随机推荐
Oracle database knowledge points (I)
From functional testing to automated testing, how did I successfully transform my salary to 15K +?
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
PMP 考试常见工具与技术点总结
How to be a professional software testing engineer? Listen to the byte five year old test
gslb(global server load balance)技术的一点理解
Anomalies seen during the interview
Introduction to thread pool
For loop
功能:编写函数fun求s=1^k+2^k +3^k + ......+N^k的值, (1的K次方到N的K次方的累加和)。
功能:将主函数中输入的字符串反序存放。例如:输入字符串“abcdefg”,则应输出“gfedcba”。
Who moved my code!
Alibaba test engineer with an annual salary of 500000 shares notes: a complete set of written tests of software testing
A little understanding of GSLB (global server load balance) technology
老姜的特点
Design of database table foreign key
Query efficiency increased by 10 times! Three optimization schemes to help you solve the deep paging problem of MySQL
Fundamentals of machine learning: feature selection with lasso
[error record] configure NDK header file path in Visual Studio (three header file paths of NDK | ASM header file path selection related to CPU architecture)
Sorry, Tencent I also refused