当前位置:网站首页>Shell script -- condition judgment
Shell script -- condition judgment
2022-07-03 04:40:00 【Saiyujun】
List of articles
Logic control — conditional
One 、 Realization of condition judgment
- if
- case
Two 、if The simple structure of
if Conditions ; then
Actions performed
Actions performed
fi
1、 The way conditions are written
- shell command
- Judge the execution status code of the command
- [ expression ]
- Number expression
- Character expression
- File directory expression
1)、 Number expression
- [ Numbers -eq Numbers ] be equal to
- [ Numbers -ne Numbers ] It's not equal to
- [ Numbers -gt Numbers ] Greater than
- [ Numbers -ge Numbers ] Greater than or equal to
- [ Numbers -lt Numbers ] Less than
- [ Numbers -le Numbers ] Less than or equal to
(1)、 Example of numeric expression script
- Auto mount CD
#!/bin/bash
#
mount -a &> /dev/null
if df -Th | grep "iso9660" &> /etc/null ; then
mount_dir=$(df -Th | grep "iso9660" | awk '{print $7}')
echo " The disc has been mounted to $mount_dir"
else
sed -ri '$a \/dev/sr0 /mnt/ iso9660 defaults 0 0' /etc/fstab
mount -a &> /dev/null
mount_name=$(df -Th | grep "iso9660" | awk '{print $1}')
echo " The CD has been successfully mounted $mount_name"
fi
- Automatically create users
#!/bin/bash/
#
read -p " Please enter a user name :" user
read -p " Please input a password " passwd
grep "^$user:" /etc/passwd &> /etc/null
if [ $? -ne 0 ]; then
useradd $user
echo $passwd | passwd --stdin $user &> /etc/null
echo "$user User created successfully "
else
echo "$user Already exists "
fi
- Judge users UID And group ID Is it consistent
#!/bin/bash/
#
read -p " Please enter a user name :" user
grep "^$user:" /etc/passwd &> /etc/null
id_num=$(id $user -u)
grp_num=$(id $user -g)
if [ $id_num -eq $grp_num ]; then
echo "Good, user ID And group ID Agreement !"
else
echo "No, user ID And group ID atypism !"
fi
- Get an alarm if the disk utilization exceeds
#!/bin/bash
#
usage=$(df -Th | grep "/$" | awk '{print $6}' | awk -F% '{print $1}')
if [ $usage -ge 60 ]; then
echo " Warning ! Warning ! The current directory usage is :${usage}% , Directory disk usage exceeds 60%!!!"
else
echo " The current directory usage is :${usage}%, The root directory usage rate does not exceed 60%"
fi
2)、 Character expression
- == The two characters are equal
- != Unequal
- [ -z character ] Judge whether the character is empty
- stay shell The space in the script also represents a certain character , If you want to if Add spaces in sentence condition judgment , Need to put “ conditional ” quotation marks
(1) Character expression script example
#!/bin/bash
#
read -p " Please input a password :" pwd1
read -p " Confirm the password :" pwd2
if [ "$pwd1" == "$pwd2" ]; then
echo " Password changed successfully !"
else
echo " Password inconsistency !"
fi
3) File directory expression
- [ -e File directory name ] Determine if the file directory exists
- [ -f File name ] Judge text file
- [ -d File name ] Determine whether it is a directory
- [ -b File name ] Determine whether it is a block device file
- [ -l File name ]
- [ -s File name ]
- [ -r File name ] [ -w File name ] [ -x File name ]
All monocular expressions support the use of ! Take the opposite [ ! -e /opt/file01 ]
2、 Single branch if
if Conditions ; then
Actions performed
Actions performed
else
Actions performed
Actions performed
fi
3、 Multiple branches if
if Conditions 1; then
Actions performed
Actions performed
elif Conditions 2; then
Actions performed
Actions performed
elif Conditions 3; then
Actions performed
Actions performed
else
Actions performed
Actions performed
fi
1)、 Many conditions
- Note that as long as one of the conditions meets the conditions, it will exit
and also
- [ Conditions 1 -a Conditions 2 ]
- [ Conditions 1 ] && [ Conditions 2 ]
or perhaps
- [ Conditions 1 -o Conditions 2 ]
- [ Conditions 1 ] || [ Conditions 2 ]
(1) Example of multi condition script
Judge user input
Linux, linux Show redhat
windows, Windows, Show Microsoft
mac, MAC, Show apple
Show others
#!/bin/bash
#
echo "---- Select the following system ----"
echo "Linux、linux"
echo "windows、Windows"
echo "mac、MAC"
echo "----------------------"
read -p " Please enter system :" system
if [ $system == linux -o $system == Linux ]; then
echo
echo " The system is :RedHat System"
elif [ $system == windows -o $system == Windows ]; then
echo
echo " The system is :Microsoft System"
elif [ $system == mac -o $system == MAC ]; then
echo
echo " The system is :Apple System"
else
echo " Other operating systems "
4、 nesting if
- Applicable to multi-level judgment
if Conditions ; then
if Conditions ; then
Actions performed
Actions performed
else
Actions performed
Actions performed
fi
else
Actions performed
Actions performed
fiw
1) Nested script example
- Delete blank lines and comment lines of the file
#!/bin/bash
#
read -p " Please enter the source file to filter :" file_name
if [ -e $file_name ]; then
if grep "^$" $file_name &> /dev/null; then
Hnumber=$(grep -n "^$" $file_name)
echo " The line number of the blank line is :"
echo $Hnumber
sed -i -e '/^$/d' -e '/^#/d' $file_name
echo " The file after deleting the blank line is :"
echo
cat $file_name
fi
else
echo " Source file does not exist !"
fi
5、case conditional
- It is applicable to judge that a variable has multiple fixed values
case Variable in
value 1)
Actions performed
Actions performed
;;
value 2)
Actions performed
Actions performed
;;
value 3)
Actions performed
Actions performed
;;
*)
Actions performed
Actions performed
;;
esac
1)、 Positional variable
$1 $2 $3 $4…$9 ${10}
- $1 The first parameter of the command ,$2 The second parameter
- $0 Command itself
- $#
- Number of parameters
case Script example
#!/bin/bash
#
if [ $# -eq 0 ]; then
echo " Command input error , Help information : $0 <linux|Linux|windows|Windows|mac|MAC>"
exit 78
fi
case $1 in
linux|Linux)
echo "RedHat"
;;
windows|Windows)
echo "Microsoft"
;;
mac|MAC)
echo "Apple"
;;
*)
echo "Others"
;;
esac
- Location variable script example
1 #!/bin/bash
2 #
3
4 nginx_file=/usr/local/nginx/sbin/nginx
5 nginx_pid=/usr/local/nginx/logs/nginx.pid
6
7 if [ -z $1 ]; then
9 exit 100
10 fi
11
12 case $1 in
13 start)
14 if [ -e $nginx_pid ]; then
15 echo "Nginx Running "
16 else
17 $nginx_file
18 if [ $? -eq 0 ]; then
19 echo "Nginx Successful launch "
20 else
21 echo "Nginx Boot failure "
22 fi
23 fi
24 ;;
25 stop)
26 if [ -e $nginx_pid ]; then
27 $nginx_file -s stop
28 if [ $? -eq 0 ]; then
29 echo "Nginx Successfully stopped "
30 else
31 echo "Nginx Stop failure "
32 fi
33 else
34 echo "Nginx Not running "
35 fi
36 ;;
37 reload)
38 kill -1 $(cat $nginx_pid)
39 if [ $? -eq 0 ]; then
40 echo "Nginx Successfully reloaded "
41 else
42 echo " Reload failed "
43 fi
44 ;;
45 restart)
46 if [ -e $nginx_pid ]; then
47 $nginx_file -s stop
48 if [ $? -eq 0 ]; then
49 echo "Nginx Restarting "
50 else
51 echo "Nginx Boot failure !!"
52 fi
53 sleep 1
54 $nginx_file
55 if [ $? -eq 0 ]; then
56 echo "Nginx Restart successful "
57 else
58 echo "Nginx Restart failed "
59 fi
62 $nginx_file -s stop
63 if [ $? -eq 0 ]; then
64 echo "Nginx Restarting "
65 else
66 echo "Nginx Boot failure !!"
67 fi
68 sleep 1
69 $nginx_file
70 if [ $? -eq 0 ]; then
71 echo "Nginx Restart successful "
72 else
73 echo "Nginx Restart failed "
74 fi
75 fi
76 ;;
77 status)
78 if [ -e $nginx_pid ]; then
79 echo "Nginx PID's $(cat $nginx_pid) Running "
80 else
81 echo "Nginx Has stopped "
82 fi
83 ;;
84 start_auto)
85 chmod a+x /etc/rc.d/rc.local
87 if [ $? -eq 0 ]; then
88 echo " Writing to boot configuration file ......"
89 source /etc/rc.d/rc.local
90 if [ $? -eq 0 ]; then
91 echo "Nginx Successful startup and self startup !"
92 fi
93 else
94 echo " Failed to write boot auto configuration file !!!"
95 fi
96 ;;
97 Cancel_startup)
98 if grep "nginx" /etc/rc.d/rc.local &> /dev/null; then
99 echo " Canceling startup "
100 sed -ri '/nginx/d' /etc/rc.d/rc.local
101 if [ $? -eq 0 ]; then
102 echo " Successfully cancel the boot auto start "
103 else
104 echo " Failed to cancel the boot auto start !!!"
105 fi
106 else
107 echo "Nginx At present, the machine does not start automatically "
108 fi
109 ;;
110 *)
111 echo " help :$0 <status|start|stop|reload|restart>"
112 exit 101
113 ;;
114 esac
边栏推荐
- stm32逆向入门
- Smart contract security audit company selection analysis and audit report resources download - domestic article
- Small sample target detection network with attention RPN and multi relationship detector (provide source code, data and download)
- [USACO 2009 Dec S]Music Notes
- AWS VPC
- 逆袭大学生的职业规划
- Design and implementation of JSP logistics center storage information management system
- 雇佣收银员(差分约束)
- Mount NFS in kubesphere
- [PCL self study: filtering] introduction and use of various filters in PCL (continuously updated)
猜你喜欢
会员积分商城系统的功能介绍
【工具跑SQL盲注】
MC Layer Target
MC Layer Target
2022 Shandong Province safety officer C certificate examination content and Shandong Province safety officer C certificate examination questions and analysis
Php+mysql registration landing page development complete code
data2vec! New milestone of unified mode
使用BENCHMARKSQL工具对kingbaseES执行灌数据提示无法找到JDBC driver
C language series - Section 3 - functions
Learning practice: comprehensive application of cycle and branch structure (I)
随机推荐
使用BENCHMARKSQL工具对KingbaseES预热数据时执行:select sys_prewarm(‘NDX_OORDER_2 ‘)报错
Jincang KFS data bidirectional synchronization scenario deployment
Leetcode simple question: check whether the array is sorted and rotated
After reviewing MySQL for a month, I was stunned when the interviewer of Alibaba asked me
Dive into deep learning - 2.1 data operation & Exercise
金仓数据库KingbaseES 插件kdb_database_link
UiPath实战(08) - 选取器(Selector)
Library management system based on SSM
stm32逆向入门
7. Integrated learning
怎么用Kotlin去提高生产力:Kotlin Tips
Contents of welder (primary) examination and welder (primary) examination in 2022
Auman Galaxy new year of the tiger appreciation meeting was held in Beijing - won the double certification of "intelligent safety" and "efficient performance" of China Automotive Research Institute
The reason why the entity class in the database is changed into hump naming
Priv-app permission异常
跨境电商多商户系统怎么选
C language series - Section 3 - functions
The programmer went to bed at 12 o'clock in the middle of the night, and the leader angrily scolded: go to bed so early, you are very good at keeping fit
A outsourcing boy's mid-2022 summary
[BMZCTF-pwn] 18-RCTF-2017-Recho