How to use if judgment in Shell?

Original: https://blog.csdn.net/weixin_46659843/article/details/124139867

1. single branch if conditional statement

then followed by the program executed after the conditions are met. You can put it after [], and use; separate. You can also write on a new line, so you do not need ";" Yes.

For example:

if   [  Conditional judgement  ] 
    then
        program 
fi
copy

1.1 example: determine whether the directory exists, and create it if it does not exist

#!/bin/bash
#date: 2022-4-13
#Description: example of if single branch statement to judge whether the directory exists
read -p "Please enter the directory to judge:" name
if [ ! -d $name ]
    then
     echo "$name Directory does not exist, creating..."
     mkdir -p $name
     echo "$name Directory creation completed."
fi
     echo "$name Directory already exists, exiting..."
copy
  1. Double branch if conditional statement
if   [  Conditional judgement  ] 
    then
        Procedures to be implemented when conditions are satisfied. 
    else
        Another procedure to be performed when the condition is not satisfied. 
fi
copy

2.1 example: monitor and automatically restart apache service scripts

In daily work, the services on the server are often down. If we do not monitor the server well, the service in the server will be down, but the administrator does not know. This is where we can write a script to listen to local services. If services are stopped or down, they can be restarted automatically. Take apache for example:

First, the port scan command and nmap port scan command are introduced,

Format: nmap -sT domain name or IP

Sub options:

-s scan -T scan all open TCP ports

The port displayed after the nmap scan must be alive.

To use the nmap command in the script, first install nmap using Yum -y install.

apache services are also installed using yum.

[root@xiaopeng ~]# cat autostart.sh 
#!/bin/bash 
port=$(nmap -sT 192.168.22.222 | grep tcp | grep http | awk '{print $2}') 
if [ "$port" == "open" ] 
    then 
        echo "$(date) httpd is ok!" >> /tmp/autostart-acc.log 
    else 
        /etc/rc.d/init.d/httpd start &> /dev/nullecho "$(date) restart httpd!!" >> /tmp/autostart-err.log 
fi
copy

(first, use the nmap command to check whether apache is enabled and assign a value to port.

Then make conditional judgment. If the service is enabled, output the current time + httpd is ok to / tmp/autostart-acc.log.

If the value of the variable port is not open, perform the operation under else. First, start the apache service, output the post startup information to the bit bucket, and then click / TMP / autostart err Log. In this script, the nmap command uses

The IP lookup port does not refer to DNS, so an error that DNS does not exist will be reported, but the result will not be affected.)

  1. Multi branch if conditional statement
if   [  Conditional judgment formula 1  ] 
    then
        When conditional judgment formula 1 is true, execute procedure 1. 
elif  [  Conditional judgment formula 2  ] 
    then
        When conditional judgment 2 is true, execute procedure 2. 
        ......(More conditions can be added) 
    else
        When all conditions are not satisfied, this procedure shall be executed finally. 
fi
copy

3.1 example: judge whether the user has entered a file or a directory

#!/bin/bash
#date:2022-4-13
#Description: judge file type
read -p "Please enter a file:" file
if [ -z $file ]
    then
     echo "Error! The file entered is empty."
elif [ ! -e $file ]
    then
     echo "Error! The file you entered does not exist."
elif [ -f $file ]
    then
     echo "$file Is a normal file"
elif [ -d $file ]
    then
     echo "$file Is a directory"
else
     echo "$file Is a different type of file"
fi
copy

4.case conditional statement

Multi branch case conditional statement

case  $Variable name  in 
    "Value 1 ") 
        If $If the variable is equal to the value 1, program 1 is executed 
    ;; 
    "Value 2 ") 
        If $Variable equals value 2, program 2 is executed 
    ;; 
        ....ellipsis... 
    *) 
        If $Execute this procedure if the value of the variable is not the above value 
    ;; 
esac
copy

4.1 example: create a startup script and let the service command manage apache

[root@xiaopeng htdocs]# vim /etc/init.d/apached
#!/bin/bash
# chkconfig: 2345 64 36         
# description: A very fast and reliable SQL database engine
httpd=/usr/local/apache2/bin/apachectl
case $1 in
start)
        $httpd start
        ;;
stop)
        $httpd stop
        ;;
restart)
        $0 stop                 
        sleep 0.05              
        $0 start
        ;;
configtest)                     
$httpd  -t
;;
*)
        echo "usage:$0 start|stop|restart|configtest."
        ;;
esac
copy

4.2 example: create a startup script and let the service command manage nginx

[root@xiaopeng conf]# vim  /etc/init.d/nginx
#!/bin/bash
#Author: liu
#chkconfig: 2345 99 33
#description: nginx server control tools
 
ngxc="/usr/local/nginx/sbin/nginx"
ngxc_fpm="/usr/local/php/sbin/php-fpm"
case "$1" in
    start)
        $ngxc -t &> /dev/null
        if [ $? -eq 0 ];then
                $ngxc
                $ngxc_fpm
                echo "nginx service start success!"
        else
                $ngxc -t
        fi
        ;;
    stop)
        $ngxc  -s  stop
        killall  php-fpm
        echo "nginx service stop success!"
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    reload)
        $ngxc -t &> /dev/null
        if [ $? -eq 0 ];then
               $ngxc  -s  reload
                pkill  -HUP  php-fpm
                echo "reload nginx config success!"
        else
                $ngxc -t
        fi
        ;;
    *)
        echo "please input stop|start|restart|reload."
        exit 1
esac
copy

Posted by captain_scarlet87 on Fri, 03 Jun 2022 06:32:21 +0530