if语句
shellif语法如下,其中confition表示条件判断式,command为程序段落
If confition
then
        command
fi
If else语法:
If confition
then
        command
else
        command
fi
If elseif语法
if confition
then
        command
elif confition
then
        Command
else
        command
fi
if语句的判断语句中,confition一般有两种表示方法:[ ]表示法和test表示法。
test命令可以对数字、字符串和文件三方面提供测试判断,比如:
test s1 = s2    # 比较字符串
test n1 -eq n2  # 比较整数
test -z string   # 判断是为空字符串
test -f path    # 判断文件是否存在
具体的测试脚本和参数可参考后续的test命令章节。
[ ]表示法与test命令的作用几乎一模一样,有一点区别是,[ ]表示法中“[”是作为命令存在,“]”是作为参数存在的,这个参数属于一个装饰参数,没有实际的作用,但是如果不传入这个参数就会发生报错,所以前面的test表示法可以改写成:
[ s1 = s2   ]  # 比较字符串
[ n1 -eq n2 ]   # 比较整数
[ -z string ]    # 判断是为空字符串
[ -f path   ]   # 判断文件是否存在
对于 [ s1 = s2 ] 而言,“[” 是命令,后面接收四个参数“s1”“=”“s2”“]”。最后的参数“]”没有实际意义。前三个有用,分别是比较参数一、比较运算符、比较参数二。但是如果参数不够,就会报错。
后续章节test命令的所有测试demo都可以依据以上方式改写成 [ ] 表示法,可自行编写测试。
2. case语句
shell中的case条件语句,与C中的switch语句语法使用类似如下:
case var in
value1)
    command
    ;;
value2)
    command
    ;;
*)
    Command
    ;;
esac
举例,shell中的breakcontinueC语言中的使用方式一样,break可以退出循环,continue结束本次循环,但是不会退出。
#!/bin/bash
echo "my first shell !"
while true
do
        echo -n "please input number(1 or 2 or 3);"
        read var
        case $var in
                1)
                        echo "1:the input number is $var"
                        break
                        ;;
                2)
                        echo "2:the input number is $var"
                        break
                        ;;
                3)
                        echo "3:the input number is $var"
                        break
                        ;;
                *)
                        echo "4:the input number is $var,it is not in range!"
                        continue
        esac
done
图片1.png
执行结果如下:
图片2.png

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    Powered by Discuz! X3.5  © 2001-2013 Comsenz Inc.