#test命令返回布尔值 test 5 -eq 5 && echo Yes || echo No # &&与(AND),执行命令1后才会继续执行命令2 test 5 -eq 15 && echo Yes || echo No # ||或(OR),执行命令1不成功则执行命令2 test 5 -ne 10 && echo Yes || echo No test-f /etc/resolv.conf && echo"File /etc/resolv.conf found." || echo"File /etc/resolv.conf not found." test-f /etc/resolv1.conf && echo"File /etc/resolv1.conf found." || echo"File /etc/resolv1.conf not found."
if结构
语法:
1 2 3 4 5 6 7
if condition then command1 command2 ... commandN fi
1 2 3 4 5 6
#!/bin/bash read -p "Enter a password" pass iftest"$pass" == "novo2017" then echo"Password verified." fi
If..else..fi
1 2 3 4 5 6 7 8
##!/bin/bash read -p "Enter a password" pass iftest"$pass" = "novo2017" then echo"Password verified." else echo"Access denied." fi
if..elif..fi
1 2 3 4 5 6 7 8 9 10 11 12 13
#!/bin/bash read -p "Enter a number : " n if [ $n-gt 0 ]; then echo"$n is a positive." elif [ $n-lt 0 ] then echo"$n is a negative." elif [ $n-eq 0 ] then echo"$n is zero number." else echo"Oops! $n is not a number." fi
命令的结束状态
1 2 3 4 5 6
date #执行一个命令 echo $? #打印该命令结束后的状态,这里会输出0 date2017 #执行一个不存在的命令 echo $? #打印该命令结束后的状态,这里会输出 ls no_this_dir # echo $? #打印该命令结束后的状态,这里会输出
#!/bin/bash read-s -p "Enter your password " pass echo iftest -z $pass then echo"No password was entered!!! Cannot verify an empty password!!!" exit 1 fi iftest"$pass" != "tom" then echo"Wrong password!" fi
文件属性比较
-d dir
如果文件存在且为目录则为true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#!/bin/bash DEST="/backup" SRC="/home"
# 确定要备份的目录存在 [ ! -d"$DEST" ] && mkdir -p "$DEST"
# 如果原目录不存在则退出... [ ! -d"$SRC" ] && { echo"$SRC directory not found. Cannot make backup to $DEST"; exit 1; }