Shell script-conditional judgment

Conditional judgment grammar format

  • Format 1: test conditional expression
  • Format 2: [Conditional expression]
  • Format 3: [[Conditional expression]] supports regular=~

note
[] And [[ ]] must have spaces on both sides

Conditional judgment related parameters

Determine file type

Judgment parameter meaning
-e Determine whether the file exists (any type of file)
-f Determine whether the file existsandIs a normal file
-d Determine whether the file exists and is a directory
-L Determine whether the file exists and is a soft link file
-b Determine whether the file exists and is a block device file
-S Determine whether the file exists and is a socket file
-c Determine whether the file exists and is a character device file
-p Determine whether the file exists and is a named pipe file
-s Determine whether the file exists and is a non-empty file (with content)

Instance

# 先判断zhu目录是否存在 存在则echo 不存在则创建
[root@maomao shell]# [ -d zhu ] && echo '存在' || mkdir zhu

# 前面加! 是非的意思
! -d 如果不存在 则创建
#!/bin/bash
back_dir=/usr/local/mysql_bcak	
if [ ! -d $back_dir ];then
       mkdir -p $back_dir
fi
       echo "开始备份..."

# -s 可以判断文件是否非空
[root@maomao shell]# [ -s free.sh ] && echo '非空' || echo "空"
非空
[root@maomao shell]# touch 123.txt
[root@maomao shell]# [ -s 123.txt ] && echo '非空' || echo "空"

test -e file                    只要文件存在条件为真
[ -d /shell/dir1 ]             判断目录是否存在,存在条件为真
[ ! -d /shell/dir1 ]        判断目录是否存在,不存在条件为真
[[ -f /shell/1.sh ]]        判断文件是否存在,并且是一个普通的文件

Determine file permissions

Judgment parameter meaning
-r Whether it is readable by the current user
-w Whether the current user can write to it
-x Is it executable by the current user
-u Is there a suid, high-level risk bit
-g Whether sgid, advanced authority mandatory bit
-k Is there a t bit, high-level permission sticky bit

Determine the new and old files

The old and new here refer toFile modification time

Judgment parameter meaning
file1 -nt file2 Compare whether file1 is newer than file2
file1 -from file2 Compare whether file1 is older than file2
file1 -ef file2 Compare whether it is the same file, or used to determine whether the hard link points to the same inode
# 创建一个硬链接
[root@maomao shell]# ln free.sh free2.sh 

[root@maomao shell]# [ free.sh -ef free2.sh ]
[root@maomao shell]# echo $?
0

Judge integer

Judgment parameter meaning
-eq equal
-born Unequal
-gt more than the
-lt Less than
-give greater or equal to
-the Less than or equal to

Instance

#!/bin/bash
# 磁盘空间警报脚本
disk_use=`df -Th |grep '/$' |awk '{print $(NF-1)}' |awk -F"%" '{print $1}'` 
mail_user=root
if [ $disk_use -gt 90 ];then
		echo "`date +%F-%H` disk:${disk_use}%" |mail -s "disk warning..." $mail_user	
fi

# 内存警报脚本
#!/bin/bash
mem_used=`free -m |grep Mem |awk '{print $3}'`
mem_total=`free -m |grep Mem |awk '{print $2}'`
mem_percent=$((mem_used*100/$mem_total))
warning_file=/shell/mem_war.txt
	rm -rf $warning_file
	#if [ $mem_percent -ge 80 ];then
	if (($mem_percent>60));then
			echo "`date +%F-%H` memory:${mem_percent}%" > $warning_file
	fi

	if [ -f $warning_file ];then
			mail -s "mem warning..." root < $warning_file
			rm -rf $warning_file
	fi

Judgment string

Judgment parameter meaning
-from Judge whether it isairString, it is true if the string length is 0
-n Judge whether it isnon emptyString, the string length is not 0 is true
string1 = string2 Determine whether the strings are equal
string1 != string2 Determine whether the strings are not equal
[root@maomao shell]# [ $USER = 'root' ];echo $?
0
[root@maomao shell]# [ $USER = 'roo' ];echo $?
1
[root@maomao shell]# [ $USER = 'root' ];echo $?
0
[root@maomao shell]# [ $USER == 'root' ];echo $?
0
[root@maomao shell]# [[ $USER == 'root' ]];echo $?
0
[root@maomao shell]# [[ "$USER" == 'root' ]];echo $?
0

Multiple condition judgment

Judgment symbol meaning For example
-a 和 && Logical and [ 1 -eq 1 -a 1 -ne 0 ] 、[ 1 -eq 1 ] && [ 1 -ne 0 ]
-o sum || Logical OR [1 -eq 1 -o 1 -ne 1] 、 [1 -eq 1] || [1 -ne 1]

Special Note:

&& before the expressionIs true, Will execute the following code

|| The previous expression为假,才会执行后面的代码

; 用于分割命令或表达式

实例

  • 数值比较
[root@maomao ~]# [ $(id -u) -eq 0 ] && echo "the user is root" || echo "the user is not root"
  • 类C风格的数值比较
注意:在(( ))中,=表示赋值;==表示判断
[root@maomao ~]# ((1==2));echo $?
[root@maomao ~]# ((1<2));echo $?
[root@maomao ~]# ((2>=1));echo $?
[root@maomao ~]# ((2!=1));echo $?
[root@maomao ~]# ((`id -u`==0));echo $?
[root@maomao ~]# ((a=123));echo $a
[root@maomao ~]# unset a
[root@maomao ~]# ((a==123));echo $?
  • 字符串比较
注意:双引号引起来,看作一个整体;===[ 字符串 ] 比较中都表示判断
[root@maomao ~]# a='hello world';b=world
[root@maomao ~]# [ $a = $b ];echo $?
[root@maomao ~]# [ "$a" = "$b" ];echo $?
[root@maomao ~]# [ "$a" != "$b" ];echo $?
[root@maomao ~]# [ "$a" !== "$b" ];echo $?        错误
[root@maomao ~]# [ "$a" == "$b" ];echo $?
[root@maomao ~]# test "$a" != "$b";echo $?


test  表达式
[ 表达式 ]
[[ 表达式 ]]

思考:[ ][[ ]] 有什么区别?

[root@maomao ~]# a=
[root@maomao ~]# test -z $a;echo $?
[root@maomao ~]# a=hello
[root@maomao ~]# test -z $a;echo $?
[root@maomao ~]# test -n $a;echo $?
[root@maomao ~]# test -n "$a";echo $?

# [ '' = $a ];echo $?
-bash: [: : unary operator expected
2
# [[ '' = $a ]];echo $?
0


[root@maomao ~]# [ 1 -eq 0 -a 1 -ne 0 ];echo $?
[root@maomao ~]# [ 1 -eq 0 && 1 -ne 0 ];echo $?
[root@maomao ~]# [[ 1 -eq 0 && 1 -ne 0 ]];echo $?

脚本实例:
批量创建用户的脚本

#!/bin/bash
# 创建用户的脚本
# by stan Z
while true
do
        read -p "Please input number:" num
        if [[ ! "$num" =~ ^[0-9]+$ || "$num" =~ ^0+$ ]];then
                echo "error number!"
        else
                break
        fi  
done
while true
do
        read -p "Please input prefix:" prefix
        if [ -z "$prefix" ];then
                echo "error prefix"
        else
                break
        fi  
done
for i in `seq $num`
do
        user=$prefix$i
        useradd $user
        echo "123" |passwd --stdin $user &>/dev/null
        if [ $? -eq 0 ];then
                echo "$user is created."
        fi
done

逻辑运算符总结

  1. 符号;和&&和||都可以用来分割命令或者表达式
  2. 分号(;)完全不考虑前面的语句是否正确执行,都会执行;号后面的内容
  3. &&符号,需要考虑&&前面的语句的正确性,前面语句正确执行才会执行&&后的内容;反之亦然
  4. ||符号,需要考虑||前面的语句的非正确性,前面语句执行错误才会执行||后内容;反之亦然
  5. 如果&&和||一起出现,从左往右依次看,按照以上原则

Guess you like

Origin blog.csdn.net/Cantevenl/article/details/115263888