Unit9-使用结构化命令

1、if-then语句

(1)
if command
then
    commands
fi
(2)
if command; then
    commands
fi
eg:
if data
then
    echo "it worked"
fi

备注:bash shell中如果命令的退出状态为0(执行成功),将执行then后面的所有指令。如果返回值非零,then后的指令将跳过。

2、if-then-else语句

if command
then
    commands
else
    commands
fi

3、嵌套if语句

if command1
then
    commands
elif command2
then
    more commands
fi

备注:if语句只能检测是否语句执行后的返回值是否为0

4、test命令

test命令提供一种检测if-then语句中不同条件的方法。
test可以评估一下3类条件

  1. 数值比较
    -eq -ge -gt -le -lt -ne
    == >= > <= < !=
  2. 字符串比较
    = != < >
    -n str1 检查str1的长度是否大于0
    -z str1 检查str1的长度是否为0
    **备注:
    1>大于和小于符号必须用转义字符,否则shell会将他们当成重定向符号,将字符串看作文件名;

    if [ $val1 \> $val2 ]
    then
        ...
    fi

    2>大于和小于顺序与在sort命令中的顺序不同;

  3. 文件比较
    test命令文件比较
    格式:
Test conditon
配合if语句的两种形式
1if test condition
then
    commands
fi
2if [ condition ]
then
    commands
fi

备注:方括号前后必须加空格

5、复合条件检查

[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]

6、if-then的高级特征

  • 双圆括号表示数学表达式
  • 双方括号表示高级字符串处理函数
    备注:双圆括号内的表达式不必转义大于号

这里写图片描述

val1=10
if (( $val1 ** 2 >90))
then
    (( val2 = $val1 ** 2))
    echo "The square of $val1 is $val2"
fi

双方括号提供了模式匹配

if [[ $USER == r* ]]
then
    echo "Hello $USER"
else
    echo "Sorry, I don't know you"
fi

7、case命令

case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值