结构化命令

1. if-then 语句

bash shell 的 if 语句会运行 if 之后的命令。如果该命令的状态吗为 0,那么 then 部分的命令就会被执行。

if command
then
     commands
fi

另一种写法
if command; then
    commands
fi
2. if-then-else 语句
if command
then
    commands
else
    commands
fi
3. 嵌套 if 语句
if pwd
then
    if ls
    then
        echo 1234
    fi
fi


if pwd1
then
    echo pwd1
else
    if ls
    then
        echo 1234
    fi
fi

elif

if command1
then
    commands
elif command2
then
    more commands
elif command3
then
    more commands
fi


if pwd1
then
    echo pwd1
elif ls
then
    echo 2222
fi
if command1
then
    commands
elif command2
then
    commands
else
    commands
fi
4. test 命令

if-then 语句只能判断命令退出状态码。
test 命令可以在 if-then 语句中测试不同的条件。如果 test 命令中列出的条件成立,则 test 命令会退出并返回状态码0。

if test condition  # 如果没有 condition,则 test 命令返回非 0 状态码
then
    commands
fi


if test abc
then
    echo 1111
else
    echo 2222
fi
输出 1111

if test ""
then
    echo 1111
else
    echo 2222
fi
输出 2222
5. 另一种测试方式,无需写明 test
if [ condition ]
then
    commands
fi

⚠️:第一个方括号之后和第二个方括号之前必须留有空格,否则会报错。
test 命令和测试条件可以判断 3 类条件:

  • 数值比较(只能处理整数)
  • 字符串比较
  • 文件比较
数值比较 描述
n1 -eq n2 n1是否等于n2
n1 -ge n2 n1是否大于等于n2
n1 -gt n2 n1是否大于n2
n1 -le n2 n1是否小于等于n2
n1 -lt n2 n1是否小于n2
n1 -ne n2 n1是否不等于n2

注意⚠️:只能处理整数


字符串比较 描述
str1 = str2 str1是否和str2相同
str1 != str2 str1是否和str2不同
str1 < str2 str1是否小于str2
str1 > str2 str1是否大于str2
-n str1 str1的长度是否不为0
-z str1 str1的长度是否为0

注意⚠️:大于号和小于号必须转义,否则会被认为是重定向符:

if [ b > a ]  # ❌ 这里会认为是重定向符
if [ b \> q ]  # ✅

注意⚠️:大于和小于的定义,与 sort 命令的规则不同:

在比较测试中,大写字母小于小写字母,但 sort 命令正好相反。
如果对数值使用了数学运算符号,那shell会将他们当成字符串。

文件比较 描述
-d file file是否存在且为目录
-e file file是否存在
-f file file是否存在且为文件
-r file file是否存在且可读
-s file file是否存在且非空
-w file file是否存在且可写
-x file file是否存在且可执行
-O file file是否存在且属当前用户所有
-G file file是否存在且默认组与当前用户相同
file1 -nt file2 file1是否比file2新 比较的是文件的创建日期
file1 -ot file2 file1是否比file2旧 比较的是文件的创建日期

⚠️:测试 -nt 或 -ot 时,务必确保文件存在。

6. 复合条件测试
if [ condition1 ] &&  [ condition2 ]
then
fi 

if [ condition1 ] ||  [ condition2 ]
then
fi 
7. if-then 的高级特性

1⃣️ 在子 shell 中执行命令的单括号

if (command)
then
fi

2⃣️ 用于数学表达式的双括号
双括号命令允许在比较过程中使用高级数学表达式,比 test 更加丰富,包含 test 的数值比较运算符。

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

双括号命令既可以在 if 语句中使用,也可以在脚本的普通命令里用来赋值:

val1 = 10
if (( $val1 ** 2 > 90 ))
then
    (( val2 = $val1 ** 2 ))
    echo "$val2"
fi
# $val2 输出为100

3⃣️ 用于高级字符串处理功能的双方括号
双方括号比 test 命令多了一个模式匹配

if [[ $BASH_VERSION == 5.* ]]
then
fi
# 判断是否以字符串 5. 开始。
8. case 命令

可以替换大量的 if-elif

if variable in
parttern1 | parttern2) commands1;;
parttern3) commands2;;
*) default commands3
esac
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容