如何使用带有多个条件的 Bash if 语句

ShellShellBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

本教程将向你介绍如何使用带有多个条件的 Bash if 语句,以提升你的 shell 脚本编写技能。你将学习如何有效地组合逻辑运算符,从而能够编写基于各种条件做出明智决策的脚本。在本实验结束时,你将能够为日常任务创建多功能的自动化工具。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("Shell")) -.-> shell/ControlFlowGroup(["Control Flow"]) shell(("Shell")) -.-> shell/AdvancedScriptingConceptsGroup(["Advanced Scripting Concepts"]) shell(("Shell")) -.-> shell/SystemInteractionandConfigurationGroup(["System Interaction and Configuration"]) shell/ControlFlowGroup -.-> shell/if_else("If-Else Statements") shell/ControlFlowGroup -.-> shell/cond_expr("Conditional Expressions") shell/AdvancedScriptingConceptsGroup -.-> shell/read_input("Reading Input") shell/SystemInteractionandConfigurationGroup -.-> shell/exit_status_checks("Exit Status Checks") subgraph Lab Skills shell/if_else -.-> lab-413763{{"如何使用带有多个条件的 Bash if 语句"}} shell/cond_expr -.-> lab-413763{{"如何使用带有多个条件的 Bash if 语句"}} shell/read_input -.-> lab-413763{{"如何使用带有多个条件的 Bash if 语句"}} shell/exit_status_checks -.-> lab-413763{{"如何使用带有多个条件的 Bash if 语句"}} end

理解 Bash if 语句的基础知识

让我们从基础开始。在 Bash 中,if 语句可帮助你的脚本根据条件的真假来决定执行什么操作。当你需要在 Ubuntu 系统上自动化执行任务时,这尤其有用。

在默认目录 /home/labex/project 中打开你的终端。你将在此处编写所有脚本。首先,通过输入以下命令创建一个名为 basic_if.sh 的简单脚本文件:

touch basic_if.sh

添加以下代码来检查文件是否存在:

#!/bin/bash
if [[ -f "testfile.txt" ]]; then
  echo "The file exists."
else
  echo "The file does not exist."
fi

此脚本使用 [[ -f "testfile.txt" ]] 来测试 testfile.txt 是否存在于当前目录中。echo 命令将根据结果显示一条消息。

要运行该脚本,需使其可执行:

chmod +x basic_if.sh

然后执行它:

./basic_if.sh

由于 testfile.txt 尚未存在,你将看到 "The file does not exist."。让我们创建该文件以查看另一种结果:

touch testfile.txt

再次运行脚本:

./basic_if.sh
basic_if.sh

现在,它应该输出 "The file exists."。此步骤向你介绍了基本结构:ifthenelsefi。双括号 [[ ]] 是现代 Bash 的一个特性,与单括号相比,它使条件测试更加可靠。

使用 AND (&&) 添加多个条件

现在,让我们通过同时检查多个条件来让你的 if 语句更加智能。你将使用 &&(逻辑与)运算符,该运算符要求所有条件都为真时,then 代码块才会执行。

再次打开 basic_if.sh,并将其内容替换为以下更新后的脚本:

#!/bin/bash
if [[ -f "testfile.txt" ]] && [[ -r "testfile.txt" ]]; then
  echo "The file exists and is readable."
else
  echo "The file is either missing or not readable."
fi

这个脚本会检查两件事:testfile.txt 是否存在(-f)以及它是否可读(-r)。只有当这两个条件都为真时,第一条消息才会显示。

运行脚本:

./basic_if.sh

由于你在步骤 1 中创建了 testfile.txt,并且它默认是可读的(因为 labex 用户拥有它),你会看到 "The file exists and is readable."。为了理解 && 运算符的工作原理,让我们测试相反的情况。更改文件的权限,使其不可读:

chmod u-r testfile.txt

再次运行脚本:

./basic_if.sh

现在,它会输出 "The file is either missing or not readable",因为第二个条件(-r)不满足。为了后续步骤,恢复文件的可读性:

chmod u+r testfile.txt

&& 运算符确保每个条件都必须通过 —— 这非常适合需要考虑多个标准的情况。

使用 OR (||) 实现灵活的条件判断

接下来,你将探索 ||(逻辑或)运算符,当 至少一个 条件为真时,它会让 then 代码块执行。当你希望在检查条件时具有灵活性时,这个运算符非常有用。

再次打开 basic_if.sh,并使用以下代码更新它:

#!/bin/bash
if [[ -f "testfile.txt" ]] || [[ -f "backup.txt" ]]; then
  echo "At least one file exists."
else
  echo "Neither file exists."
fi

这个脚本会检查 testfile.txtbackup.txt 是否存在。由于 testfile.txt 已经在你的目录中,运行脚本:

./basic_if.sh

你会看到 "At least one file exists."。现在,删除 testfile.txt 以测试 || 逻辑:

rm testfile.txt

再次运行脚本:

./basic_if.sh

它会输出 "Neither file exists",因为两个文件都不存在。创建 backup.txt 以使逻辑或条件成立:

touch backup.txt
./basic_if.sh

现在,它又会显示 "At least one file exists"。当任何一个条件为真就足够时,|| 运算符非常实用。

组合使用 AND 和 OR 运算符

让我们将 &&|| 组合起来,实现更复杂的逻辑。你将检查文件是否存在并满足特定条件,同时设置一个备用条件。

再次打开 basic_if.sh,并使用以下代码更新它:

#!/bin/bash
if [[ -f "testfile.txt" ]] && [[ -r "testfile.txt" ]] || [[ -f "backup.txt" ]]; then
  echo "Either testfile.txt is readable or backup.txt exists."
else
  echo "No suitable file found."
fi

这个脚本会检查 testfile.txt 是否存在 并且 可读,或者 backup.txt 是否存在。重新创建 testfile.txt

touch testfile.txt

运行脚本:

./basic_if.sh

它会输出 "Either testfile.txt is readable or backup.txt exists",因为 testfile.txt 满足这两个条件。删除 testfile.txt 并保留 backup.txt

rm testfile.txt
./basic_if.sh

同样的消息会出现,因为 backup.txt 满足 || 条件。也删除 backup.txt

rm backup.txt
./basic_if.sh

现在,它会显示 "No suitable file found."。这一步展示了如何混合使用运算符来做出细致的决策。

将条件应用于实际任务

最后,让我们在实际场景中运用你所学的知识:验证用户输入。你将编写一个脚本来检查一个数字是否在某个范围内。

创建一个名为 number_check.sh 的新脚本:

touch number_check.sh
chmod +x number_check.sh

添加以下代码:

#!/bin/bash
read -p "Enter a number between 1 and 10: " number
if [[ "$number" -ge 1 ]] && [[ "$number" -le 10 ]]; then
  echo "Valid number: $number"
else
  echo "Invalid number. Please enter a value between 1 and 10."
fi

这个脚本会提示你输入一个数字,然后使用 && 运算符确保该数字在 1 到 10 之间(包含 1 和 10)。运行脚本:

./number_check.sh

输入 5 并按下 Enter 键。你会看到 "Valid number: 5"。再次运行脚本并输入 15,它会回应 "Invalid number. Please enter a value between 1 and 10."。这是处理用户输入的一种实用方法,可确保你的脚本仅处理有效数据。

总结

在这个实验中,你已经掌握了如何使用 &&|| 运算符编写带有多个条件的 Bash if 语句。从检查文件属性到验证用户输入,你已经编写了能够根据复杂条件做出决策的脚本。这些技能使你能够在 Ubuntu 系统上创建满足各种需求的可靠自动化工具。