当前位置:网站首页>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
边栏推荐
- Ffmpeg mix
- 有道云笔记
- Why does I start with =1? How does this code work?
- C language series - Section 3 - functions
- 会员积分商城系统的功能介绍
- [PHP vulnerability weak type] basic knowledge, PHP weak equality, error reporting and bypassing
- 2022 tea master (intermediate) examination questions and tea master (intermediate) examination skills
- Priv-app permission异常
- 普通本科大学生活避坑指南
- 2022-02-13 (347. Top k high frequency elements)
猜你喜欢

使用BENCHMARKSQL工具对kingbaseES执行灌数据提示无法找到JDBC driver

Php+mysql registration landing page development complete code

Function introduction of member points mall system
![[PCL self study: filtering] introduction and use of various filters in PCL (continuously updated)](/img/36/53886b9d3b98f744be2b6aa6b5d3eb.jpg)
[PCL self study: filtering] introduction and use of various filters in PCL (continuously updated)
![[XSS bypass - protection strategy] understand the protection strategy and better bypass](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[XSS bypass - protection strategy] understand the protection strategy and better bypass

FISCO bcos zero knowledge proof Fiat Shamir instance source code

Web - Information Collection

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

Leetcode simple problem delete an element to strictly increment the array

Bugku CTF daily question baby_ flag. txt
随机推荐
data2vec! New milestone of unified mode
Summary of training competition (Lao Li's collection of questions)
Internationalization and localization, dark mode and dark mode in compose
[set theory] binary relationship (special relationship type | empty relationship | identity relationship | global relationship | divisive relationship | size relationship)
General undergraduate college life pit avoidance Guide
Library management system based on SSM
Web security - CSRF (token)
Games101 Lesson 9 shading 3 Notes
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
带有注意力RPN和多关系检测器的小样本目标检测网络(提供源码和数据及下载)...
Triangular rasterization
怎么用Kotlin去提高生产力:Kotlin Tips
Arthas watch grabs a field / attribute of the input parameter
Bugku CTF daily question baby_ flag. txt
Joint set search: merge intervals and ask whether two numbers are in the same set
FuncS sh file not found when using the benchmarksql tool to test kingbases
[SQL injection point] location and judgment of the injection point
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
Php+mysql registration landing page development complete code
Reptile exercise 03