When we write a program, we often need to judge the execution result of the previous step, so the judgment needs to be realized by using if statement.
if statement is mainly used for judgment in our program.
1, if syntax
1.1 single branch if
if condition;then Command to execute 1 Command to execute 2 Command to execute 3 ... fi # The above syntax can be replaced by one line of code [ Condition information ] && Execute command
Alarm for monitoring disk usage exceeding 80%
[root@localhost ~]# cat disk_monitor.sh #!/usr/bin/env bash disk_use=$(df -P |grep '/$' |awk '{print $5}' |awk -F% '{print $1}') if [ $disk_use -gt 89 ];then echo "warning:Not enough hard disk space" fi [root@localhost ~]# sh disk_monitor.sh warning:Not enough hard disk space
Note: in the if test, you can also execute the command and judge according to the return value of the command
[root@localhost ~]# if cd /etc;then echo yes;fi yes
1.2 if double branch
if condition;then Command to execute 1 Command to execute 2 Command to execute 3 ... else Command to execute 1 Command to execute 2 Command to execute 3 ... fi # The above syntax can be replaced by one line of code [ Condition information ] && xxx || yyy
1.2.1 simulated Login
[root@localhost ~]# cat login.sh #!/bin/bash User="bertwu" Passwd="123" read -p "Please enter user name:" user read -p "Please input a password:" passwd if [ $User == "$user" -a $Passwd == "$passwd" ];then echo "Login succeeded" && exit else echo "Wrong user name or password" fi
1.3 multi branch if
if condition;then Command to execute 1 Command to execute 2 Command to execute 3 ... elif condition;then Command to execute 1 Command to execute 2 Command to execute 3 ... elif condition;then Command to execute 1 Command to execute 2 Command to execute 3 ... ... else Command to execute 1 Command to execute 2 Command to execute 3 ... fi
1.3.1 age:
[root@manager scripts]# cat age.sh Age=78 while true do read -p "Please enter age:" age if [[ ! $age =~ ^[0-9]+$ ]];then # Non numeric prompt user to re-enter echo "please input a digit" continue fi if (($age > $Age));then echo "too big" continue elif (($age < $Age));then echo " too small" continue else echo "you are greate, get it" break fi done
1.3.2 score query
#!/bin/bash read -p "your score>>> " score [[ ! $score =~ ^[0-9]+$ ]] && echo "please enter a number" && exit if [ $score -ge 90 ];then echo "excellent" elif [ $score -ge 70 ];then echo "good" elif [ $score -ge 60 ];then echo "commonly" else echo "Poor" fi
1.4 judge whether it is a number
[root@manager scripts]# cat isdigit.sh read -p "Please enter a numeric value: " num while : do if [[ $num =~ ^[0-9]+$ ]];then break else read -p "Not a number, please re-enter the value: " num fi done echo "The number you entered is: $num"
1.5 pass in the file and judge the file type
[root@manager scripts]# cat test_file.sh #!/bin/bash if [ -L $1 ];then echo "$1 is a link" elif [ -d $1 ];then echo "$1 is a directory" elif [ -b $1 ];then echo "$1 is a block" elif [ -f $1 ];then echo "$1 is a file" else echo "unknow" fi [root@manager scripts]# sh test_file.sh /bin /bin is a link [root@manager scripts]# sh test_file.sh /etc /etc is a directory
1.6 judge whether the user exists
[root@manager scripts]# cat check_user.sh #/bin/bash id $1 &>/dev/null if (($?==0));then echo "$1 existence" else echo "$1 non-existent" fi [root@manager scripts]# sh check_user.sh root root existence [root@manager scripts]# sh check_user.sh tom tom existence [root@manager scripts]# sh check_user.sh xx xx non-existent
1.7 check whether the httpd software is installed. If not, install it
[root@manager scripts]# cat check_httpd.sh #!/bin/bash rpm -qa | grep httpd &>/dev/null if [ $? -eq 0 ];then echo "httpd Already installed" else yum install httpd -y &>/dev/null fi
1.8 judge the status of port 80. If it is not turned on, restart it
[root@manager scripts]# cat check_port.sh #!/bin/bash netstat -lntp | egrep ":80 " &>/dev/null if (($?==0));then echo "80 Port started" else echo "80 port down,Restarting" systemctl restart httpd &>/dev/null sleep 3 netstat -lntp | egrep ":80 " &>/dev/null if (($?==0));then echo "80 Port started successfully" else echo "Startup failed" fi fi
1.9 write monitoring script and concurrent mail
- The remaining space in the root partition is less than 10%
- Or the free space of memory is less than 30%
- Send an alarm email to the user bertwu. The email contains information about usage
[root@manager scripts]# cat monitor.sh #!bin/bash disk_used=$(df | grep '/$' | awk -F '%' '{print $1}' | awk '{print $NF}') # Root partition disk usage Men_used=$(free -m | grep "Mem" | awk '{print $3*100/$2}') # Memory usage if (( $disk_used > 90 ));then echo "The disk has been used for 90 years%,Beyond the warning line" | mail -s "Disk alarm" bertwu@qq.com fi if [ $(echo "$Men_used > 70" | bc) -eq 1 ];then echo "The memory has been used for 70 years%,Beyond the warning line" | mail -s "Memory alarm" bertwu@qq.com fi
mailx configuration
[root@localhost ~]# yum install mailx -y [root@localhost ~]# cat /etc/mail.rc set from=xxx@qq.com set smtp=smtps://smtp.qq.com:465 set smtp-auth-user=xxx@qq.com set smtp-auth-password="xxxxxxxxxx" set smtp-auth=login set ssl-verify=ignore set nss-config-dir=/etc/pki/nssdb/
Explanation of terms:
set from: Set sender set smtp: Set external STMP The server set smtp-auth-user: set up STMP User name (usually full email address) set smtp-auth-password: set up SMTP password,Login required xxx@qq.com In settings->account->open POP3/SMTP service->Get password
1.10 backup script
Requirement 1: backup files to / backup/system/filename_2021-8-29, if the directory does not exist, it will be created automatically.
1. Source file, allowing the user to input manually;
2. Target location: / backup/system / judge whether the directory exists. If it does not exist, create it;
[root@manager scripts]# cat backup.sh dir=/backup/system read -p "Please enter the source file path:" src if [ ! -d $src ] && [ ! -f $src ];then echo "file does not exist" exit fi if [ ! -s $src ];then echo "File cannot be empty" exit fi if [ ! -d $dir ];then mkdir $dir -p fi filename=$(echo ${src##*/}) cp -rpv $src $dir/${filename}_$(date +%F)
1.11 lock the execution document
When a script is running, in principle, other people are not allowed to operate the script, so it is necessary to lock the script
[root@manager scripts]# cat lock.sh #!/bin/bash if [ -f /tmp/run.lock ];then echo "The script is running..." exit fi # Lock touch /tmp/run.lock # Business code sleep 30 # Unlock after operation if [ -f /tmp/run.lock ];then rm -rf /tmp/run.lock fi
1.12 viewing service operation status
[root@manager scripts]# cat status.sh #!/bin/bash if [ ! $# -eq 1 ];then echo "USAGE: $0 { nginx | mysql | httpd| haproxy | zabbix-agent}" exit fi systemctl status $1 &>/dev/null # Check the status: 0 has been started normally, 3 has not been started, 4. Not installed flag=$? if [ $flag -eq 0 ];then echo "$1 Normal service" elif [ $flag -eq 3 ];then echo "$1 Service not started" elif [ $flag -eq 4 ];then echo "$1 Not installed" read -p "Installation required $1 Services:[yes|no]" action if [ ${action:=no} == "yes" ];then yum install $1 -y else exit fi fi
1.13 obtaining process details
1. First pass a parameter, 1, the name of the service;
2. Judge whether the process exists. If it does not exist, warn and exit the script;
2. Obtain the pid related information of the process; ps aux|grep $1
3. active (running) of the service is also required
4. The value needs to be extracted from the running user: pid, STAT, command command
[root@manager scripts]# cat process.sh #bin/bash read -p "Please enter the service name:" name systemctl status $name &>/dev/null flag=$? if [ $flag -eq 4 ];then read -p "The service is not installed, do you want to install it[yes|no default:yes]" action if [ ${action:=yes} == "yes" ];then yum install $name -y if [ $? -eq 0 ];then echo "$name Installation succeeded" else echo "$name Installation failed" exit fi else echo "Failed to get information!" exit fi systemctl start $name if [ $? -eq 0 ];then echo "$name Start successful" else echo "Startup failed, no information was obtained" fi else [ $flag -eq 3 ] systemctl start $name fi # Re judge the service status systemctl status $name &>/dev/null flag=$? if [ $flag -ne 0 ];then echo "The service is hopeless" exit else # Get process details # Business logic service_runtime=$(systemctl status $name | grep Active | awk '{print $2,$3}') echo "current $name The status of the process is:" echo "$name : $service_runtime" echo "****************************************************" echo "current $name Details of the process are: " ps aux|grep $name | grep -v grep | grep -v "$$" | awk 'BEGIN {printf "%-15s%-15s%-20s\n","User of the process","Process PID","Process command"} {printf "%-20s%-20d%-20s\n",$1,$2,$NF}' > /tmp/${name}.txt echo "***************************************************" cat /tmp/${name}.txt rm -rf /tmp/${name}.txt fi
1.14 three data sorting
1. Control can only input three parameters;
2. Change row to column display mode;
3.sort;
[root@manager scripts]# cat sort.sh #/bin/bash if [ $# -ne 3 ];then echo "Please enter three numbers" exit fi if [[ $1 =~ ^[0-9]+$ ]] && [[ $2 =~ ^[0-9]+$ ]] && [[ $3 =~ ^[0-9]+$ ]];then echo "$1 $2 $3" | xargs -n1 | sort else echo "Must be a pure number" exit fi
1.15 judge whether the user input is empty
[root@manager scripts]# cat input.sh #!/bin/bash read -p "Please enter:" action if [ -z $action ];then echo "Illegal input" exit fi echo "What you entered is: $action"
1.16 check whether selinux is disabled
[root@manager scripts]# cat selinux.sh #!/bin/bash status=$(grep "^SELINUX=" /etc/selinux/config | awk -F "=" '{print $2}') if [ ! $status == "disabled" ];then sed -i '/^SELINUX=/c SELINUX=disabled' /etc/selinux/config echo "Closed selinux" else echo "selinux Already closed" fi
1.17 creating users
Requirements: write a script to create a user.
1. Prompt the user to enter the prefix to create the user, which must be in English.
2. Prompt the user to enter a suffix, which must be a number. 010203
3. If there is no problem with prefix and suffix, create a user.
4. And the password is random;
[root@manager scripts]# cat adduser.sh #!/bin/bash read -p "Please enter a user name, which must start with a letter and end with a number:" username if [[ $username =~ ^[a-z]+ ]] && [[ $username =~ [0-9]+$ ]];then id $username &>/dev/null if (( $?==0 ));then echo "User already exists" exit else useradd $username password=$(echo $RANDOM | md5sum | cut -b 1-6) echo $password | passwd --stdin $username fi echo $username:$password >> /opt/pass.txt else echo "Illegal user name input" fi
1.18 backup
Requirements: back up and compress all contents of the / etc directory on the first day of each month and store them in the / opt/bak directory
2021_10_10_etc.tar.gz, the script name is fileback, and it is stored in the home directory of / root.
[root@localhost scripts]# cat fileback.sh dir=/opt/bak lock_file=/tmp/back.lock log_file=/var/log/$0.log log_format=$(date +%F_%T):$(hostname):$0 # Determine running identity if [ ! $USER == "root" ];then echo "Insufficient permissions, please use root Run as" echo "$log_formart" >> $log_file exit else echo "$log_format $USER Start running backup script" >> $log_file fi if [ -f $lock_file ];then echo "The script runs regularly, please wait..." exit fi # Lock touch /tmp/back.lock # Determine whether the backup directory exists if [ ! -d $dir ];then mkdir $dir fi # tar package / etc echo "$log_formart Start packaging" >> $log_file cd / && tar czf $dir/$(date +%F)_etc.tar.gz etc if [ -f $dir/$(date +%F)_etc.tar.gz ];then echo "$log_format $USER User packaging/etc Directory success" >> $log_file else echo "$log_format $USER User packaging/etc/Directory failed" >> $log_file fi # Unlock rm -rf $lock_file
2, case
Case statement is similar to if multi branch judgment statement, which is mainly used for multi condition judgment; However, case is more convenient than if multi branch condition judgment in Shell script.
In the production environment, we will make various plans according to "one problem", and then load different plans according to the user's choice. For example, for the start and stop script of the service, we must first write the plans for start, stop and restart, and then load different plans according to the user's choice.
2.1 case syntax
case variable in Mode 1) Command sequence 1 ;; Mode 2) Command sequence 2 ;; Mode 3) Command sequence 3 ;; *) Command sequence after no match esac
[root@localhost scripts]# cat case1.sh #!/bin/bash cat <<EOF **************** ** 1. backup ** ** 2. copy ** ** 3. quit ** **************** EOF read -p "Input a choose: " OP case $OP in 1|backup) echo "BACKUP......" ;; 2|copy) echo "COPY....." ;; 3|quit) exit ;; *) echo error! esac
Example 1
[root@localhost scripts]# cat user.sh read -p "input username:" -t 10 username if [ -z $username ];then username="default" fi case $username in root) echo "Administrator user" ;; bertwu) echo "Ordinary users" ;; default) echo "Default user" ;; *) echo "No permission" esac
2.2 writing nginx startup and shutdown scripts
[root@manager scripts]# cat nginx_stat.sh #!/bin/bash . /etc/init.d/functions args=$1 fun(){ [ $? -eq 0 ] && action "Nginx $args is ok" /bin/true || action "Nginx $args is filed" /bin/false } case $1 in start) netstat -lntp | grep nginx &>/dev/null if [ $? -eq 0 ] then echo "Nginx is runing..." else /usr/sbin/nginx fun fi ;; stop) /usr/sbin/nginx -s stop fun ;; reload) /usr/sbin/nginx -s reload fun ;; restart) netstat -lntp | grep nginx &>/dev/null if [ $? -ne 0 ] then /usr/sbin/nginx [ $? -eq 0 ] && echo "Nginx start is ok" || echo "Nginx start is failed" else /usr/sbin/nginx -s stop [ $? -eq 0 ] && echo "Nginx stop is ok" || echo "Nginx stop is failed" sleep 2 /usr/sbin/nginx fun fi ;; status) netstat -lntp | grep nginx &>/dev/null if [ $? -eq 0 ] then echo "Nginx is runing ..." else echo "Nginx is not runing ..." fi ;; *) echo "Usage: $0 {start|stop|status|restart|reload}" exit 2 esac
2.3 writing rsync startup and shutdown scripts
[root@rsync ~]# cat rsyncd.sh #!/bin/bash . /etc/init.d/functions fun(){ [ $? -eq 0 ] && action "Rsyncd $args is ok" /bin/true || action "Rsync $args is failed" /bin/false } start_rsync(){ args=start netstat -lntp | grep rsync &>/dev/null if [ $? -eq 0 ];then action "rsync is running....." /bin/true else /usr/bin/rsync --daemon fun fi } stop_rsync(){ args=stop netstat -lntp | grep rsync &>/dev/null if [ $? -ne 0 ];then action "rsync is not running....." else pid=$(ps aux | grep "[r]sync --daemon" | awk '{print $2}') # rsync process number kill -9 $pid fun fi } case $1 in start) start_rsync ;; stop) stop_rsync ;; restart) stop_rsync start_rsync ;; status) systemctl status rsyncd | grep Active ;; *) echo "USAGE $0 [start | stop | restart | status ]" esac