Bash 中的单行 if...else

MD Aminul Islam 2023年1月30日
  1. Bash 中 if ... else 的多行示例
  2. Bash 中 if ... else 的单行示例
Bash 中的单行 if...else

条件语句是决定依赖于各种条件的任何程序的基本部分。在本文中,我们将了解 if ... else 条件语句以及如何创建单行 if ... else 语句。

此外,我们将看到必要的示例和解释,以使主题更容易。

众所周知,Bash 中 if ... else 的一般语法是:

if [ YOUR_CONDITION_HERE ]
then
    // Block of code when the condition matches
else
   // Default block of code
fi

现在,在我们讨论 if ... else 语句的单行格式之前,我们需要了解这个条件语句的多行格式。

Bash 中 if ... else 的多行示例

下面的示例将检查一个值是否大于 15。为此,我们将使用 if ... else 语句和多行格式。

现在,我们示例的代码将如下所示:

num=10
if [ $num -gt 15 ]
then
    echo "The provided value is greater than 15"
else
   echo "The provided value is less than 15"
fi

运行示例代码后,你将获得以下输出。

The provided value is less than 15

记住代码 -gt 的意思是大于。

Bash 中 if ... else 的单行示例

现在我们将看到上述示例的单行版本。此示例将提供类似的输出,但代码结构将是单行。

类似的代码如下所示。

num=16
if [ $num -gt 15 ]; then echo "The value is greater than 15"; else echo "The value is less than 15"; fi

你必须在这里做的唯一一件事就是包含一个符号 ;。所以从上面的例子中,我们可以很容易地发现单行 if ... else 的一般语法类似于:

if [ YOUR_CONDTION_HERE ]; then # Block of code when the condition matches; else # Default block of code; fi

运行示例代码后,你将获得以下示例。

The value is greater than 15

在使用嵌套的 if ... else 或复杂条件时,将其写在一行非常困难。并且出错的可能性最高。

此外,如果你使用单行 if ... else,将很难发现你代码中的错误和漏洞。

本文中的所有代码都是用 Bash 编写的。它只能在 Linux Shell 环境中运行。

作者: MD Aminul Islam
MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

相关文章 - Bash Condition