«

If-then语句

一个摆子 发布于 阅读:38 Linux


if-then格式:

if command
then
    commands
fi

另外一种格式:

if command; then
conmmands
fi

if语句会运行if后面的命令,如果该命令的退出码是0(该命令成功运行),在执行then后的命令,如果退出码不是0,则不会执行then后的命令,fi表示if语句结束。
例如:

#!/bin/bash
if pwd
then
    echo "这是当前目录"
fi

if-then-else格式:

if command
then
    commands
else
    commands
fi

当if返回0时执行then中的语句,当if返回不是0时执行else中的语句。
嵌套if格式:

if command1
then
    commands
elif command2
then
    more commands
fi

test命令格式:

test condition

condition是test命令要测试的一系列参数和值。如果test命令中的条件成立,test就退出并返回0,如果不成立test退出并返回非零状态码。
test命令搭配if-then语句

if test condition
then
    commands
fi

另一种无需声明test命令的方法:

if [ condition ]
then
    commands
fi

方括号定义了测试条件,第一个方括号之后和第二个方括号之前必须加上一个空格,否则就会报错

if-then允许使用布尔逻辑来组合测试

第一种布尔运算使用AND布尔运算符来组合两个条件,要让then部分执行,两个条件都必须满足。

if-then的两个高级特性

双括号命令格式

((expression))

expression可以是任意的数学赋值或比较表达式

双括号命令符号

符号 描述
val++ 后增
val-- 后减
++val 先增
--val 先减
! 逻辑求反
~ 位求反
** 幂运算
<< 左位移
>> 右位移
& 位布尔和
| 位布尔或
&& 逻辑和
|| 逻辑或

双方括号命令格式

[[ expression ]]

双方括号提供了针对字符串比较的高级特性。expression可使用模式匹配。

case命令
case命令格式

case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac

case命令会将指定的变量与不同模式进行比较,如果变量和模式匹配,那么shell执行为该模式指定的命令,“*”会捕获所有与已知模式不匹配的值。

交流群:

请先 登录 再评论