Shell script -- condition judgment

Logic control - condition judgment

1, Realization of conditional judgment

  • if
  • case

2, Simple structure of if

if condition ; then
	Actions performed
	Actions performed
fi

1. Writing of conditions

  • shell command
    • Determine the execution status code of the command
  • [expression]
    • Numeric expression
    • Character expression
    • File directory expression

1) , numeric expression

  • [number -eq number] equals
  • [number ne number] is not equal to
  • [number gt] greater than
  • [number -ge number] greater than or equal to
  • [number - lt number] less than
  • [number -le number] 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 "Disc 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 "Successfully mounted the disc $mount_name"
fi
  • Automatically create users
#!/bin/bash/
#

read -p "Please enter 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 whether the user UID is consistent with the group ID
#!/bin/bash/
#

read -p "Please enter 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 utilization exceeds 60%!!!"
else
        echo "The current directory usage is: ${usage}%, The root directory usage rate does not exceed 60%%"
fi

2) , character expression

  • ==Two characters are equal
  • != Unequal
  • [- z character] judge whether the character is empty
  • In the shell script, a space also represents a character. If you want to add a space to the conditional judgment of the if statement, you need to add double quotation marks to the "conditional judgment"

(1) Character expression script example

#!/bin/bash
#

read -p "Please input a password:" pwd1
read -p "Confirm password:" pwd2
if [ "$pwd1" == "$pwd2" ]; then
        echo "Password modification succeeded!"
else
        echo "The password is inconsistent!"
fi    

3) File directory expression

  • [- e file directory name] judge whether the file directory exists
  • [- f file name] judge text file
  • [- d file name] determines whether it is a directory
  • [- b file name] determines 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 are supported! Reverse [! - e /opt/file01]

2. Single branch if

if condition; then
    Actions performed
    Actions performed
else
	Actions performed
	Actions performed
fi

3. if multi branch

if Condition 1; then
	Actions performed
	Actions performed 
elif Condition 2; then 
	Actions performed
	Actions performed
elif Condition 3; then 
	Actions performed
	Actions performed
else
	Actions performed
	Actions performed
fi 

1) . multi conditional writing

  • Note that multiple conditions. As long as one of them meets the conditions, it will exit
  • and also

    • [condition 1 -a condition 2]
    • [condition 1] & & [condition 2]
  • Or or

    • [condition 1 -o condition 2]
    • [condition 1] | [condition 2]

(1) Multi condition script example

  • Judge user input

    Linux, linux displays redhat

    windows, Windows, display Microsoft

    mac, MAC, display apple

    Show other

#!/bin/bash
#
echo "----Select the following systems----"
echo "Linux,linux"
echo "windows,Windows"
echo "mac,MAC"
echo "----------------------"
read -p "Please enter the 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. Nested if

  • Applicable to multi-layer judgment
if  condition; then
      if  condition; then
             Actions performed
             Actions performed
      else
             Actions performed
             Actions performed
      fi
else
        Actions performed
        Actions performed
fiw

1) Nested script example

  • Delete empty lines and comment lines from 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 condition judgment

  • 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) . location variable

  • $1 $2 $3 $4...$9 ${10}

    • First argument of $1 command, $2 second argument
    • $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 Successfully started"
 20                 else
 21                         echo "Nginx Start failed"
 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 failed"
 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 Start failed!!"
 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 Start failed!!"
 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 canceled the startup and self startup"
103                 else
104                         echo "Failed to cancel startup and self startup!!!"
105                 fi
106         else
107                 echo "Nginx At present, it does not start automatically"
108         fi
109         ;;
110         *)
111         echo "help: $0 <status|start|stop|reload|restart>"
112         exit 101
113         ;;
114 esac

nginx/d' /etc/rc.d/rc.local
101 if [ $? -eq 0 ]; then
102 echo "successful cancellation of startup and startup"
103 else
104 echo "failed to cancel boot auto start!!!"
105 fi
106 else
107 echo "Nginx does not start automatically at present"
108 fi
109 ;;
110 *)
111 echo "help: $0 < status|start|stop|reload|restart >"
112 exit 101
113 ;;
114 esac

Keywords: Linux bash

Added by greenie__ on Sat, 12 Feb 2022 11:17:48 +0200