文章目录
一、shell中的运算1.1、数学比较运算(整数比较)1.2、字符串比较运算(加引号)1.3、文件的比较与检查(-e, -d, -f ...)二、if条件语句2.1、if语句2.2、if-then-else语句2.3、if-then-elif语句三、if 高级运用(扩展)3.1、if (( 数学表达式 ))3.1、if [[ 字符串匹配 ]]一、shell中的运算
1.1、数学比较运算(整数比较)
shell中的数学比较运算符如下,区别于常规的 >, <, = 运算:(具体含义可通过man test命令进行查看)
equal | no equal | less than | greater than | less than or equal | greater than or equal
$?——代表上一个命令执行后的退出状态echo $?——如果返回值是0,就是执行成功;如果是返回值是0以外的值,就是失败。
[marc@localhost Shell]$ test 1 -eq 1;echo $?0[marc@localhost Shell]$ test 1 -ne 1;echo $?1[marc@localhost Shell]$ test 1 -gt 1;echo $?1[marc@localhost Shell]$ test 1 -lt 1;echo $?1[marc@localhost Shell]$ test 1 -ge 1;echo $?0[marc@localhost Shell]$ test 1 -le 1;echo $?0
1.2、字符串比较运算(加引号)
shell中的字符串比较运算符如下,比较时字符串需要用引号引起来(具体含义可通过man test命令进行查看)。
[marc@localhost Shell]$ test $USER=='marc';echo $?0[marc@localhost Shell]$ test $USER != 'marc';echo $?#区别于赋值=, 变量与比较字符之间可以有空格1[marc@localhost Shell]$ test -n "";echo $?1[marc@localhost Shell]$ test -z "";echo $?0[marc@localhost Shell]$ test -z "$HOME";echo $?1
1.3、文件的比较与检查(-e, -d, -f …)
同整形数字一样,文件类型也可使用test命令进行判断,也可使用if条件语句进行判断;具体选项含义也可通过man test命令进行查看。
[marc@localhost Shell]$ test -e time.sh;echo $?0[marc@localhost Shell]$ test -d time.sh;echo $?1[marc@localhost Shell]$ test -s time.sh;echo $?0[marc@localhost Shell]$ test -r time.sh;echo $?0[marc@localhost Shell]$ test -x time.sh;echo $?1
二、if条件语句
2.1、if语句
格式:(shell的if语句格式不同于其它语言)
注意:if关键字与中括号之间必须有空格,中括号与conditions之间也必须有空格,不然会报错。
if [ conditions ] # 注意空格 多条件判断if [ condition ] || [ condition ] || [ condition ]thencommands# 代码块fi
#!bin/bashif [ $USER != "root" ]thenecho "ERROR: need to be root so that" #执行命令exit 1 #退出脚本fi[marc@localhost Shell]$ bash if1.sh ERROR: need to be root so that
2.2、if-then-else语句
if [ conditions ] # 注意空格thencommands1# 代码块elsecommands2# 代码块fi
#!bin/bashif [ $USER == "root" ]then echo "Hello, root!"elseecho "Hello, guest!"fi[marc@localhost Shell]$ bash if2.sh Hello, guest!
2.3、if-then-elif语句
if [ conditions ] # 注意空格thencommands1# 代码块elif [ ] thencommands2# 代码块elsecommands3# 代码块 fi
#!bin/bashif [ $1 -gt $2 ] # 这里的 $1 与 $2 变量的值通过命令行直接传参thenecho "$1 > $2"elif [ $1 -lt $2 ]then echo "$1 < $2"elseecho "$1 = $2"fi[marc@localhost Shell]$ bash if3.sh 3 5 # 命令行直接传参3 < 5[marc@localhost Shell]$ bash if3.sh 3 33 = 3[marc@localhost Shell]$ bash if3.sh 3 13 > 1
三、if 高级运用(扩展)
3.1、if (( 数学表达式 ))
常规的if条件语句后使用中括号[ ]来添加conditions,但是也可以通过使用==双圆括号(( ))==取代中括号,双圆括号中需为数学表达式。
#!bin/bashif (( 100%3+1 > 10 )) thenecho "yes"elseecho "no"fi[marc@localhost Shell]$ bash if4.shno
3.1、if [[ 字符串匹配 ]]
for i in rr1 rr2 cc rr3 # 分别将字符串rr1 rr2 cc rr3赋值给变量idoif [[ $i == r* ]]# 通过通配符*匹配r开头的字符串thenecho "$i"fidone[marc@localhost Shell]$ bash if4.sh rr1rr2rr3