Shell programming - Judgment

Posted by rn14 on Fri, 11 Feb 2022 01:59:43 +0100

1.Shell condition test

1.1. Numerical comparison:

  • Operator:

    • gt: greater than
    • lt: less than
    • eq: equal to
    • ne: not equal to
    • ge: greater than or equal to
    • le: less than or equal to
  • Test syntax:

    • Mode 1: test conditional expression
    [root@VM-0-17-centos ~]# test 8 -ge 2 / / no value is returned when the command is executed directly
    [root@VM-0-17-centos ~]# 
    [root@VM-0-17-centos ~]# test 8 -ge 0;echo $?  
    0
    
    • Expression: [conditional space] must be between expression: [2]
    [root@VM-0-17-centos ~]# [7 -eq 7] / / there is no return value when the command is executed directly
    [root@VM-0-17-centos ~]# [ 7 -eq 7 ];echo $?
    0
    
    • Method 3: [[conditional expression]] (there must be a space between conditional expression and [[], and there must be no space between two [])
    [root@VM-0-17-centos ~]# [[ 7 -eq 7 ]];echo $?
    0
    [root@VM-0-17-centos ~]# [[7 -eq 7]] / / directly executing this command does not return a value
    [root@VM-0-17-centos ~]# 
    
  • Test script:

read -p "Input password:" ps
if [ ${#ps} -lt 7 ]
    then
    	echo "too short"
else
    echo "too long"
fi  // Indicates the end of if

tips:

  • Get variable length:
[root@VM-0-17-centos ~]# a="psj"
[root@VM-0-17-centos ~]# echo ${#a} / / be sure to add {}
3
  • echo $? Indicates that the return value of the previous command is returned. A return value of 0 indicates that the previous command is executed normally

1.2. Document test:

  • Operator:
    • -f filename: returns true when filename exists
    • -b pathname: returns true when pathname exists and is a directory
    • -w pathname: returns true when pathname exists and is writable
    • ...
  • Test syntax: three methods in the same value comparison section
  • Test script:
read -p "Enter backup directory:" dir
if [ -d $dir ]
    then
    	echo "$dir Can backup"
else
    echo "$dir Cannot be backed up"
fi

1.3. String judgment:

  • Operator:
    • =: equal to, can also be used==
    • !=: Not equal to, can also be used==
  • Test syntax: three methods in the same value comparison section
  • Test script:
read -p "Input string:" str
if [ $str = "ok" ]
    then
    	echo "ok!"
else
    echo "not ok!"
fi

tips:

  • Judge whether the character length is 0:
[root@VM-0-17-centos ~]# a=""
[root@VM-0-17-centos ~]# [ -z "$a"];echo $?  // Equivalent to [${#a} - EQ 0]; echo $?

1.4.and and or:

  • Operator:

    • &&: logical and, you can use - a instead

    • ||: logical or, you can use - o instead

  • Test syntax: three methods in the same value comparison section

  • Test script:

read -p "Input password:" pass
# if [ "${#pass}" -gt 1 -a "${#pass}" -lt 5 ]
# if [ "${#pass}" -gt 1  &&  "${#Pass} "- LT 5] / / an error is reported. If & & is used, only [[]] can be used
if [[ "${#pass}" -gt 1  &&  "${#pass}" -lt 5 && "$pass" =~ [a-z] ]]
    then
    	echo "nice"
else
    echo "bad"
fi

tips:

  • If special characters are used in the judgment expression, only [[]] can be used. For example, ~ (= ~ is a fuzzy query of regular expression) and $$, if [] is used, an error will be reported

2. Process control

  • Single branch:
if [ expression ]
then 
// Execute statement
fi
  • Dual branch: the user enters the user name. If the user name does not exist, the user will be created
read -p "enter one user name:" name
id $name &> /dev/null  // The original execution id will output the content, but it will not output the content after & > / dev / null, but can you use $? display
if [ $? -ne 0 ]
	then
		useradd $name
else
	echo "User already exists!"
fi
  • Multi branch: obtain the current time for judgment output
hour=`date +%H`  // Gets the number of hours of the current time
if [ $hour -ge 6 -a $hour -le 10 ]
        then
                echo "morning"
elif [ $hour -ge 11 -a $hour -le 13 ]
        then
                echo "noon"
elif [ $hour -ge 14 -a $hour -le 18 ]
        then
                echo "afternoon"
else
        echo "night"
fi
  • Nested structure:
read -p "enter one user name:" user
# Determine whether the user exists
if id $user &> /dev/null  // If you use the command directly in if, you cannot add [] on both sides
then
        echo "User already exists"
else
        echo "Ready to create user"
        read -p "Enter new user password:" pass
        if [ ${#pass} -ge 7 ]
        then
                useradd $user
                echo $pass | passwd --stdin $user
        else
                echo "The password does not meet the requirements"
        fi
fi

tips:

  • Detect syntax errors in the script:
# Use parameter - n to detect syntax errors
[root@VM-0-17-centos ~]# bash -n test.sh / / if there is a syntax error, the message will be output. If there is no error, the script will not be executed
test.sh: line 4: syntax error near unexpected token `then'
test.sh: line 4: `then'
# Use the parameter - vx to execute the command line by line, and a plus sign will appear if the command is executed successfully
[root@VM-0-17-centos ~]# bash -vx test.sh 
read -p "enter one user name:" user
+ read -p enter one user name: user
 enter one user name:root
# Determine whether the user exists
if id $user &> /dev/null 
then
	echo "User already exists"
else 
	echo "Ready to create user"
	read -p "Enter new user password:" pass
	if [ ${#pass} -ge 7 ]
	then 
		useradd $user
		echo $pass | passwd --stdin $user 
	else
		echo "The password does not meet the requirements"
	fi
fi
+ id root
+ echo User already exists
 User already exists
  • The judgment does not support floating-point values

3. Pattern matching: case

  • Simple pattern matching cases:
read -p "Enter the user name to delete:" user
read -p "Are you sure to delete?:" action

case $action in
Y|y|yes|YES|YeS)
        userdel -r "$user"
        echo "$user Deleted"
;;

*)
        echo "bye"
;;

esac
  • Simple JumpServer:
web1=192.168.142.149
web2=192.168.142.150
mysql=192.168.142.151

# Print menu
cat <<EOF
1.web1
2.web2
3.mysql
EOF

read -p "Enter number:" num

case $num in
1)
        ssh psj@web1
;;

2)
        ssh psj@web1
;;

3)
        ssh psj@web1
;;

*)
        echo "bye"
;;
esac

Topics: Linux shell