当前位置:网站首页>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
边栏推荐
- 2-Redis架构设计到使用场景-四种部署运行模式(下)
- [cloud native topic -48]:kubesphere cloud Governance - operation - overview of multi tenant concept
- [common error] custom IP instantiation error
- 【.NET+MQTT】. Net6 environment to achieve mqtt communication, as well as bilateral message subscription and publishing code demonstration of server and client
- HackTheBox-baby breaking grad
- Self study software testing. To what extent can you go out and find a job?
- Employees' turnover intention is under the control of the company. After the dispute, the monitoring system developer quietly removed the relevant services
- Design of database table foreign key
- Beijing invites reporters and media
- Who moved my code!
猜你喜欢

AI 助力艺术设计抄袭检索新突破!刘芳教授团队论文被多媒体顶级会议ACM MM录用

1-Redis架构设计到使用场景-四种部署运行模式(上)

Print diamond pattern
![[dynamic programming] leetcode 53: maximum subarray sum](/img/f0/80357f9ffc556f3ed4d3aa0901bb1d.jpg)
[dynamic programming] leetcode 53: maximum subarray sum

Software testers, how can you quickly improve your testing skills? Ten minutes to teach you

Analysis and solution of lazyinitializationexception

Employees' turnover intention is under the control of the company. After the dispute, the monitoring system developer quietly removed the relevant services

打印菱形图案

How to use AHAS to ensure the stability of Web services?

AI helps make new breakthroughs in art design plagiarism retrieval! Professor Liu Fang's team paper was employed by ACM mm, a multimedia top-level conference
随机推荐
Interview script of Software Test Engineer
The difference between objects and objects
Leetcode 121 best time to buy and sell stock (simple)
A dichotomy of Valentine's Day
How to use AHAS to ensure the stability of Web services?
Functions and arrays of shell scripts
Mongodb learning notes: command line tools
7.1 learning content
For loop
8. Go implementation of string conversion integer (ATOI) and leetcode
12. Go implementation of integer to Roman numeral and leetcode
使用dnSpy对无源码EXE或DLL进行反编译并且修改
Wechat official account and synchronization assistant
Why use get/set instead of exposing properties
Query efficiency increased by 10 times! Three optimization schemes to help you solve the deep paging problem of MySQL
Delete all elements with a value of Y. The values of array elements and y are entered by the main function through the keyboard.
Fundamentals of machine learning: feature selection with lasso
[common error] custom IP instantiation error
Cesiumjs 2022^ source code interpretation [8] - resource encapsulation and multithreading
机器学习基础:用 Lasso 做特征选择