世界杯门票_托马斯穆勒世界杯进球数 - noh16.com

世界杯门票_托马斯穆勒世界杯进球数 - noh16.com

shape
  • Home
  • 法国世界杯名单
  • Bash Shell 中的条件表达式

Bash Shell 中的条件表达式

  • 2025-09-17 18:45:01
  • admin

Bash 中的 if 语句

内置 Bash 条件

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 参考手册。

-f 检查文件是否存在并且它是一个普通文件。

-d 检查提供的参数是否是目录。

-h 检查提供的参数是否是符号链接。

-s 检查文件是否存在且不为空。

-r 检查文件是否可读。

-w 检查文件是否可写。

-x 检查文件是否可执行。

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

假设我们比较两个文件 - 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

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

-ef 确保两个参数引用相同的设备和 inode 号。

!= 确保两个参数不相等。

< 检查第一个参数是否按字母顺序排在第二个参数之前。

> 检查第一个参数是否按字母顺序排在第二个之后。

-eq 假设两个参数都是整数并检查它们是否相等。

-ne 假设两个参数都是整数并检查它们是否不相等。

-lt 假设两个参数都是整数并检查第一个小于第二个。可以使用 -le 检查它们是否相等。

-gt 假定两个参数都是整数并检查第一个是否大于第二个。可以使用 -ge 检查它们是否相等。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

<<<
Previous Post
波霸牛 - Palworld幻兽帕鲁中文百科WIKI

Copyright © 2088 世界杯门票_托马斯穆勒世界杯进球数 - noh16.com All Rights Reserved.

友情链接