迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 >

Bash Shell 中的条件表达式

作者:迹忆客 最近更新:2023/03/17 浏览次数:

Bash 作为一种编程语言并不是大多数程序员的首选,尤其是对于 Python 和 C 等更常见的语言。

编写编程结构以使用 if 语句根据条件执行命令或使用 for 循环具有多个参数的同一命令会很有帮助。

本教程将介绍 Bash 中的 if 语句,重点介绍 if 语句中使用的各种条件表达式。

Bash 中的 if 语句

Bash 中 if 语句的一般语法如下。

if condition; then
    do-if-true;
elif second-condition; then
    do-else-if-true
elif third-condition; then
    do-else-if-third-true
else
    do-else-false
fi

条件本身可以有不同的语法,具体取决于所需的条件。

  • 如果你想使用命令的输出作为条件,例如 grep 文件的内容以查看它是否包含某个子字符串,你可以将命令放在 if 关键字之后,如下所示。
if greq -q "string" file.txt; then
    echo "string exists in file.txt."
else
    echo "string does not exist in file.txt."
fi
  • [ "$s" = "string" ] 检查变量 $s 是否包含值 string。它也等价于 test "$s" = "string",其中 test 有效地替换了方括号。
if [ "$s" = "string" ]; then
    echo "string is equivalent to \$s"
else
    echo "string is not equivalent to \$s"
fi
  • 你甚至可以执行算术运算,例如检查文件中的预期文件数或行数是否确定,或者一个目录中的数量是否小于或大于另一个目录的数量。

    我们用一对括号来做到这一点。

a=$(ls dir_a | wc -l)
b=$(ls dir_b | wc -l)
if (( a < b )); then
    echo "Directory a has fewer files than directory b."
elif (( a > b )); then
    echo "Directory a has more files than directory b."
else
    echo "Directory a has the same number of files as that of directory b."
fi

内置 Bash 条件

有时,运行一个单独的程序来检查像文件存在、修改日期和大小这样简单的事情是乏味且耗费资源的,因此 Bash 可以像 if 语句一样直接检查这些属性。

以下标志检查这些属性的存在或不存在,将有效的真或假结果返回给 if 语句。

例如,要检查命令是否没有输出,我们可以将其输出视为字符串,并使用 -z 标志检查该字符串的长度是否为零,如下所示。

out=$(bash print-if-error.sh)
if [[ -z $out ]]; then
    echo "The script ran successfully."
else
    echo "The script produced the following errors: "
    echo $out
fi

要获得条件的倒数,你可以使用! NOT 运算符,或使用此标志的相反形式,即 -n,或根本没有标志,因为非空字符串在 Bash if 语句中可以表现为

out=$(bash print-if-error.sh)
if [[ $out ]]; then
    echo "The script produced the following errors: "
    echo $out
else
    echo "The script ran successfully."
fi

下面解释了一些其他有用的标志,解释参考了 GNU Bash 参考手册

对于带有两个参数的标志,例如比较运算符,第一个参数出现在标志之前,而第二个参数出现在标志之后。

假设我们比较两个文件 - a.txt 和 b.txt - 看看哪个更新,带有 -nt 标志。反过来将检查它是否更旧,使用 -ot

out=$(bash print-if-error.sh)
if [[ a.txt -nt b.txt ]]; then
    echo "a.txt is newer than b.txt."
else
    echo "a.txt is older or the same age as b.txt."
fi

其他这样的二操作数标志如下。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便