当前位置:网站首页>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
边栏推荐
- Summary of training competition (Lao Li's collection of questions)
- 使用BENCHMARKSQL工具对kingbaseES执行灌数据提示无法找到JDBC driver
- [set theory] binary relationship (special relationship type | empty relationship | identity relationship | global relationship | divisive relationship | size relationship)
- [BMZCTF-pwn] 18-RCTF-2017-Recho
- Factor stock selection scoring model
- Some information about the developer environment in Chengdu
- [set theory] binary relationship (binary relationship notation | binary relationship from a to B | number of binary relationships | example of binary relationship)
- 怎么用Kotlin去提高生产力:Kotlin Tips
- stm32逆向入门
- 会员积分商城系统的功能介绍
猜你喜欢

Truncated sentences of leetcode simple questions

Handling record of electric skateboard detained by traffic police

Games101 Lesson 9 shading 3 Notes

UiPath实战(08) - 选取器(Selector)

关于开学的准备与专业认知

Two drawing interfaces - 1 Matlab style interface

MC Layer Target

When using the benchmarksql tool to preheat data for kingbasees, execute: select sys_ Prewarm ('ndx_oorder_2 ') error

消息队列(MQ)介绍

Integration of Android high-frequency interview questions (including reference answers)
随机推荐
Learning practice: comprehensive application of cycle and branch structure (I)
Leetcode simple problem delete an element to strictly increment the array
Preparation for school and professional cognition
C language self-made Games: Sanzi (tic tac toe chess) intelligent chess supplement
Basic use of continuous integration server Jenkins
消息队列(MQ)介绍
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
Leetcode simple question: check whether the array is sorted and rotated
The least operation of leetcode simple problem makes the array increment
Joint search set: the number of points in connected blocks (the number of points in a set)
[luatos sensor] 1 light sensing bh1750
The usage of micro service project swagger aggregation document shows all micro service addresses in the form of swagger grouping
Integration of Android high-frequency interview questions (including reference answers)
2022 registration of G2 utility boiler stoker examination and G2 utility boiler stoker reexamination examination
Leetcode simple question: check whether two string arrays are equal
[BMZCTF-pwn] 20-secret_ file
[fxcg] inflation differences will still lead to the differentiation of monetary policies in various countries
MC Layer Target
使用BENCHMARKSQL工具对kingbaseES执行灌数据提示无法找到JDBC driver
[USACO 2009 Dec S]Music Notes