9.5 条件测试与流程控制

本节介绍如何判断条件以及使用常见的流程控制语句。

test 命令

test 用于检查条件,通过数值、字符串和文件测试。

数值测试

参数 说明
-eq 等于则为真
-ne 不等
-gt 大于
-ge 大于等于
-lt 小于
-le 小于等于

示例:

num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo '两个数相等!'
else
    echo '两个数不相等!'
fi

[] 可以执行算术运算,例如 $[a+b]

字符串测试

参数 说明
= 等于
!= 不等
-z 字符串 长度为零则为真
-n 字符串 长度不为零则为真

示例:

num1="ru1noob"
num2="runoob"
if test $num1 = $num2
then
    echo '两个字符串相等!'
else
    echo '两个字符串不相等!'
fi

文件测试

参数 说明
-e 文件名 存在
-r 文件名 可读
-w 文件名 可写
-x 文件名 可执行
-s 文件名 非空
-d 文件名 目录
-f 文件名 普通文件
-c 文件名 字符设备
-b 文件名 块设备

示例:

cd /bin
if test -e ./bash
then
    echo '文件已存在!'
else
    echo '文件不存在!'
fi

逻辑操作符:

  • -a
  • -o
  • !

优先级 ! > -a > -o

if 语句

基本 if

if condition
then
    commands
fi

if … else

if condition
then
    commands
else
    commands
fi

if … elif … else

if condition1
then
    commands
elif condition2
then
    commands
else
    commands
fi

示例:

a=10
b=20
if [ $a == $b ]
then
   echo "a 等于 b"
elif [ $a -gt $b ]
then
   echo "a 大于 b"
elif [ $a -lt $b ]
then
   echo "a 小于 b"
else
   echo "没有符合的条件"
fi

iftest 常结合使用。

for 循环

for var in item1 item2 ... itemN
do
    commands
done

如果省略 in list,则循环 $@ 参数列表。

示例:

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

while 循环

while condition
do
    commands
done

示例:

int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

读取键盘示例:

echo '按下 <CTRL-D> 退出'
echo -n '输入你最喜欢的网站名: '
while read FILM
do
    echo "是的!$FILM 是一个好网站"
done

无限循环

while :
do
    commands
done
# 或者
while true
do
    commands
done
# 或者
for (( ; ; ))

done

results matching ""

    No results matching ""