Shell script integer value comparison, logic test, if statement

1. Conditional test operation

[conditional expression]

(1) document test
[file or directory]
-d: Whether the directory is directory (test)
-e: Test whether the directory or file exists (Exist)
-f: Test whether it is a file
-r: Test whether the current user has permission to read,
-w: Test whether the current user has permission to write
-x: Test whether the executable permission is set
 

Test whether the directory / media exists, $? A return value of 0 indicates that this directory exists

[ -d  /media/  ]

echo $?

ls -ld /media/

If $? A non-zero return value indicates that this directory does not exist

[ -d /media/cdrom ]

echo $?

ld -ld  /media/cdrom

Test whether the directory exists. The output result is more intuitive. The output "yes" indicates that the directory exists

[ -d /media/ ] && echo "yes"

No "yes" output indicates that the directory does not exist

[ -d /media/cdrom ] && echo "yes"

(2) integer value comparison
Judge the relationship between the first number and the second number according to the given two integer values
[integer 1 - operator 2]
-eq: the first number is equal to the second number
-ne: the first number is not equal to the second number
-gt: the first number is greater than the second number
- It: the first number is less than the second number
-le: the first number is less than or equal to the second number
-ge: the first number is greater than or equal to the second number

 

Judge the number of currently logged in users, and output "too many" when there are more than 5 users

who |wc -l

unum=`who | wc -l`

[ $unum -gt 5 ] && echo "too many"

Judge the size of currently available free memory (buffers/cache). When it is lower than 2048MB, output the specific value

Freecc=$(free -m | grep "Mem:" |awk '{print  $6}')

[ $Freecc -lt 1024 ] && echo ${Freecc}MB

(3) string comparison
String comparison is usually used to check whether user input, system environment, etc. meet the conditions
[string 1 operator string 2]
=: the first string is the same as the second string
!=: The first string is different from the second string. Where '! The "sign" indicates negation
-z: Check whether the string is null (Zero). Variables that are not defined or assigned null values will be treated as empty strings

The user enters "yes" or "no" to confirm a task

read -p "shi fou fu gai xian  you wen jian (yse/no)?" ACK
 [ $ACK = "yes" ] && echo "fu gai"


read -p "shi fou fugai xianyouwenjian(yes/no)?" ACK
[ $ACK = "no" ] && echo "bu fu gai"

(4) logic test
Logical testing refers to judging the dependency between two or more conditions
Command 1 operator 2
&&: and
|: or
 !: Logical no, negative
 

Judge whether the kernel version of the current linux system is greater than 2.4.

View kernel

uname -r

judge

A=$(uname -r | awk -F.  '{print  $1}')
B=$(uname -r | awk -F.  '{print  $2}')
[ $A -ge 3  ]  &&  [  $B -gt 4 ] && echo "fu he yaoqiu"

2. Structure of IF statement

(1) single branch if
The corresponding code will be executed only when the condition is true, otherwise no operation will be performed

Syntax format:
if conditional test operation
then
Command sequence
fi

Determine the mount point directory. If it does not exist, it will be created automatically

vim cdrom.sh
 
#!/bin/bash
MOUNT_DIR="/meida/cdrom/"
if [ ! -d $MOUNT_DIR ]
then
        mkdir -p $MOUNT_DIR
fi

chmod +x cdrom.sh
./cdrom.sh

 

Judge whether the current user is root. If not, report an error and execute the "exit # 1" exit script without executing other codes

vim /opt/root.sh
#!/bin/bash
if [ "$USER" !="root" ]
then
        echo "Error: non root User, insufficient permission!"
        exit 1
fi
fdisk -l /dev/sda


su lisi
exit 


chmod +x /opt/root.sh

Switch user execution su -user name   /opt/root.sh

Re switch root User authentication



 

 

(2) double branch if statement
It is required to perform different operations for the two cases of "condition is true" and "condition is not true"
Syntax format:
if conditional test operation
then
Command sequence 1
else
Command sequence 2
fi
Judge whether the target host is alive and display the detection results

vim ping.sh

#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if [ $? -eq 0 ]
then
echo "Host $1 is up."
else
echo "Host $1 is down."
fi


ifconfig ens33 192.168.1.10     (Temporary modification IP (address)

 ./ping.sh 192.168.1.10        (ping own IP (address)

Display is up Indicates success

 

Check whether the vsftpd service is running. If it is running, list the listening address and PID number; Otherwise, the output prompts "warning, vsftpd service unavailable". (insert the linux system installation CD and install the vsftpd package)
 

vim vsftpd.sh

#!/bin/bash
systemctl status vsftpd &> /dev/nll
if [ $? -eq 0 ]
then
echo "Listening address:$(netstat -anpt | grep vsftpd | awk '{print $4}')"
echo "process PID number:$(pgrep -x vsftpd)"
else
echo "warning:vsftpd Service Unavailable!"
fi


chmod +x vsftpd.sh

 ./vsftpd.sh

Display warning when not started: vsftpd service is unavailable, success
When starting, it displays: listening port:: 21, process PID number: 61072, then it is successful

(3) Multi branch if statement
Because if statements can perform operations respectively according to whether the test results are true or not, they can be nested and used for multiple judgments.
Syntax format:
if condition test operation 1
then
Command sequence 1
elif condition test operation 2
then
Command sequence 2
else
Command sequence 3
fi


According to the different test scores entered, we can distinguish three grades: excellent, qualified and unqualified

vim gradediv.sh


#!/bin/bash
read -p "Please enter your score(0-100):" GRADE
if [ $GRADE -ge 85 ] &&  [ $GRADE -le 100  ]
then
        echo "$GRADE branch,excellent!"
elif [ $GRADE -ge 70 ] &&  [ $GRADE -le 84  ]
then
        echo "$GRADE branch,qualified!"
else
        echo "$GRADE branch,unqualified!"
fi


chmod +x gradediv.sh

./gradediv.sh

 

Tags: Linux Operation & Maintenance Database MySQL

Posted by Sneo on Fri, 20 May 2022 07:41:43 +0300