Moving ahead from our previous tutorial on arrays in shell scripts, let’s understand how we can use if-else in shell scripts.

从上一章有关shell脚本中数组的教程开始,让我们了解如何在shell脚本中使用if-else。

Conditional programming is an important part of any programming language because executing every single statement in our program is, more often than not, undesirable.

条件编程是任何编程语言的重要组成部分,因为执行我们程序中的每条语句通常都是不希望的。

And we need a way to conditionally execute statements. The if-else in shell scripts serves this exact situation.

我们需要一种有条件地执行语句的方法。 shell脚本中的if-else可以满足这种情况。

Shell脚本中的条件 (Conditions in Shell Scripts)

One of the most important parts of conditional programming is the if-else statements. An if-else statement allows you to execute iterative conditional statements in your code.

条件编程的最重要部分之一是if-else语句。 if-else语句允许您在代码中执行迭代条件语句。

We use if-else in shell scripts when we wish to evaluate a condition, then decide to execute one set between two or more sets of statements using the result.

当我们希望评估条件时,我们在外壳脚本中使用if-else,然后决定使用结果在两组或更多组语句之间执行一组。

This essentially allows us to choose a response to the result which our conditional expression evaluates to.

从本质上讲,这使我们可以选择对条件表达式求值结果的响应。

shell脚本中的if-else如何工作? (How does if-else in shell scripts work?)

Now we know what is an if-else function and why is it important for any programmer, regardless of their domain. To understand if-else in shell scripts, we need to break down the working of the conditional function.

现在我们知道什么是if-else函数,以及为什么它对任何程序员都重要,无论其领域如何。 要了解shell脚本中的if-else,我们需要分解条件函数的工作。

Let us have a look at the syntax of the if-else condition block.

让我们看一下if-else条件块的语法。


if [condition]
thenstatement1
elsestatement2
fi

Here we have four keywords, namely if, then, else and fi.

这里我们有四个关键字,即if,then,elsefi。

  1. The keyword if is followed by a condition.关键字if后跟一个条件
  2. This condition is evaluated to decide which statement will be executed by the processor.评估该条件以确定处理器将执行哪个语句。
  3. If the condition evaluates to TRUE, the processor will execute the statement(s) followed by the keyword then. In the syntax, it is mentioned as statement1.如果条件评估为TRUE,则处理器将执行语句,然后执行关键字then 。 在语法中,它被称为statement1
  4. In a case where the condition evaluates to FALSE, the processor will execute the statement(s) followed by the keyword else. This is denoted as statement2 in the function syntax.在条件评估为FALSE的情况下,处理器将执行语句,然后执行关键字else 。 这在函数语法中表示为statement2

An important thing to keep in mind is that, like C programming, shell scripting is case sensitive. Hence, you need to be careful while using the keywords in your code.

要记住的重要一点是,与C编程一样,shell脚本也区分大小写。 因此,在代码中使用关键字时需要小心。

如何在shell脚本中使用if-else (How to use if-else in shell script)

It is easy to see the syntax of a function and believe you know how to use it. But it is always a better choice to understand a function through examples because they help you understand the role that different aspects of a function play.

很容易看到函数的语法,并相信您知道如何使用它。 但是,通过示例理解函数始终是一个更好的选择,因为它们可以帮助您理解函数的不同方面所扮演的角色。

Here are some useful examples of if-else in shell scripts to give you a better idea of how to use this tool.

以下是一些有用的shell脚本中if-else示例,可让您更好地了解如何使用此工具。

Command Description
&& Logical AND
|| Logical OR
$0 Argument 0 i.e. the command that’s used to run the script
$1 First argument (change number to access further arguments)
-eq Equality check
-ne Inequality check
-lt Less Than
-le Less Than or Equal
-gt Greater Than
-ge Greater Than or Equal
命令 描述
&& 逻辑与
|| 逻辑或
$ 0 参数0,即用于运行脚本的命令
$ 1 第一个参数(更改编号以访问其他参数)
-eq 平等检查
-ne 不平等检查
-lt 少于
-le 小于或等于
-gt 比...更棒
-ge 大于或等于

1.使用if-else检查两个数字是否相等 (1. Using if-else to check whether two numbers are equal)

When trying to understand the working of a function like if-else in a shell script, it is good to start things simple. Here, we initialize two variables a and b, then use the if-else function to check if the two variables are equal. The bash script should look as follows for this task.

当试图了解shell脚本中if-else之类的功能的工作时,最好从简单的角度开始。 在这里,我们初始化两个变量a和b,然后使用if-else函数检查两个变量是否相等。 此任务的bash脚本应如下所示。


#!/bin/bash
m=1
n=2if [ $n -eq $m ]
thenecho "Both variables are the same"
elseecho "Both variables are different"
fi

Output:

输出:


Both variables are different

2.使用if-else比较两个值 (2. Using if-else to compare two values)

The more common use of if-else in shell scripts is for comparing two values. Comparing a variable against another variable or a fixed value helps is used in a variety of cases by all sorts of programmers.

shell脚本中if-else的更常见用法是比较两个值。 将变量与另一个变量或固定值进行比较会在各种情况下被各种程序员使用。

For the sake of this example, we will be initializing two variables and using the if-else function to find the variable which is greater than the other.

为了这个示例,我们将初始化两个变量,并使用if-else函数查找比另一个大的变量。


#!/bin/bash
a=2
b=7
if [ $a -ge $b ]
thenecho "The variable 'a' is greater than the variable 'b'."
elseecho "The variable 'b' is greater than the variable 'a'."
fi

Output:

输出:


The variable 'b' is greater than the variable 'a'.

3.使用if-else检查数字是否为偶数 (3. Using if-else to check whether a number is even)

Sometimes we come across situations where we need to deal with and differentiate between even and odd numbers. This can be done with if-else in shell scripts if we take the help of the modulus operator.

有时我们遇到需要处理和区分偶数和奇数的情况。 如果我们借助模数运算符,可以在shell脚本中使用if-else完成此操作。

The modulus operator divides a number with a divisor and returns the remainder.

模运算符将数字除以除数,然后返回余数。

As we know all even numbers are a multiple of 2, we can use the following shell script to check for us whether a number is even or odd.

众所周知,所有偶数都是2的倍数,我们可以使用以下shell脚本来检查数字是偶数还是奇数。


#!/bin/bash
n=10
if [ $((n%2))==0 ]
thenecho "The number is even."
elseecho "The number is odd."
fi

Output:

输出:


The number is even

As you can see, we’ve enclosed a part of the condition within double brackets. That’s because we need the modulus operation to be performed before the condition is checked.

如您所见,我们已经将条件的一部分括在双括号中。 这是因为我们需要在检查条件之前执行模运算。

Also, enclosing in double brackets runs statements in C-style allowing you to process some C-style commands within bash scripts.

另外,用双括号括起来可以使用C风格的语句,使您可以在bash脚本中处理某些C风格的命令。

4.使用if-else作为简单密码提示 (4. Using if-else as a simple password prompt)

The if-else function is known for its versatility and range of application. In this example, we will use if-else in shell script to make the interface for a password prompt.

if-else函数以其多功能性和应用范围而闻名。 在此示例中,我们将在shell脚本中使用if-else来创建密码提示的界面。

To do this, we will ask the user to enter the password and store it in the variable pass. 

为此,我们将要求用户输入密码并将其存储在变量pass中。

If it matches the pre-defined password, which is ‘password’ in this example, the user will get the output as -“The password is correct”.

如果它与预定义的密码(在此示例中为“ password”)匹配,则用户将获得以下输出:“密码正确”。

Else, the shell script will tell the user that the password was incorrect and ask them to try again.

否则,shell脚本将告诉用户密码不正确,并要求他们重试。


#!/bin/bash
echo "Enter password"
read pass
if [ $pass="password" ]
thenecho "The password is correct."
elseecho "The password is incorrect, try again."
fi
Bash Password
Bash密码

结论 (Conclusion)

The function of if-else in shell script is an important asset for shell programmers. It is the best tool to use when you need to execute a set of statements based on pre-defined conditions.

Shell脚本中if-else的功能是Shell程序员的重要资产。 当您需要根据预定义条件执行一组语句时,它是最好的工具。

The if-else block is one, if not the most essential part of conditional programming. By regulating the execution of specific statements you not only make your code more efficient but you also free up the precious time which the processor might have wasted executing statements which are unnecessary for a specific case.

if-else块是条件编程中最重要的部分(如果不是)。 通过规范特定语句的执行,您不仅可以提高代码效率,还可以释放处理器可能浪费的宝贵时间,这对于特定情况是不必要的。

We hope this tutorial was able to help you understand how to use the if-else function. If you have any queries, feedback or suggestions, feel free to reach out to us in the comments below.

我们希望本教程能够帮助您了解如何使用if-else函数。 如果您有任何疑问,反馈或建议,请随时通过以下评论与我们联系。

翻译自: https://www.journaldev.com/38145/if-else-in-shell-scripts

如何在Shell脚本中使用if-else?相关推荐

  1. linux脚本中如何读取文件,如何在Shell脚本中逐行读取文件

    原标题:如何在Shell脚本中逐行读取文件 在这里,我们学习Shell脚本中的3种方法来逐行读取文件. 方法一.使用输入重定向 逐行读取文件的最简单方法是在while循环中使用输入重定向. 为了演示, ...

  2. 如何在脚本中输入密码 linux,如何在shell脚本中为用户分配密码

    本篇文章给大家介绍的内容是关于如何在shell脚本中为用户分配密码,下面我们来看具体的内容. 我们先来看一下命令echo | passwd –stdin 例如: 使用以下命令更改shell脚本中用户j ...

  3. 如何在 Shell 脚本中执行语法检查调试模式

    我们开启了 Shell 脚本调试系列文章,先是解释了不同的调试选项,下面介绍如何启用shell调试模式. 写完脚本后,建议在运行脚本之前先检查脚本中的语法,而不是查看它们的输出以确认它们是否正常工作. ...

  4. linux脚本done报错,linux – 如何在shell脚本中处理错误/异常?

    下面是我在bash中执行的脚本.它工作正常. fileexist=0 for i in $( ls /data/read-only/clv/daily/Finished-HADOOP_EXPORT_& ...

  5. shell脚本中执行命令_如何在Shell脚本中执行命令?

    shell脚本中执行命令 Shell is a command-line interpreter that allows the user to interact with the system. I ...

  6. shell有bool运算么_如何在shell脚本中声明和使用布尔变量?

    我尝试使用以下语法在shell脚本中声明一个布尔变量:variable=$false variable=$true 它是否正确? 另外,如果我想更新该变量,我会使用相同的语法? 最后,使用布尔变量作为 ...

  7. linux下带.d的文件夹,linux – 如何在shell脚本中包含目录中的所有文件(在本例中为/etc/init.d/iptables)...

    我在不同的ubuntu服务器上有一个/etc/init.d/iptables start | stop | restart脚本(这是一个普通的 shell脚本) 对于每个新服务,我必须编辑并插入一行来 ...

  8. 如何在Shell脚本中漂亮地打印JSON?

    是否有(Unix)Shell脚本以易于理解的格式格式化JSON? 基本上,我希望它可以转换以下内容: { "foo": "lorem", "bar&q ...

  9. 如何在shell脚本中定义数组及遍历

    问题起源:脚本中定义多个监控模块,代码重复率高,仅仅模块名不同,所以思考如何精简代码? 1.如何定义数组及访问数组: var=(1 2 3 4 5) var=(a b c d e) var=('1' ...

最新文章

  1. 【BLE】TLSR8258开发记录之15--模拟FATFS
  2. 启明云端分享:产品应用上,怎么选型ESP-12F\ESP-12E\ESP-12S\ESP-07S这四个模块
  3. 防火墙(5)——五表
  4. AtCoder Beginner Contest 175总结
  5. C语言编杂志程序,c语言程序错误修改
  6. 程序代码错误检测_错误检测代码
  7. C++:拷贝构造函数与深/浅拷贝
  8. php登陆+链接+验证,php+ajax验证登录跳转登录的实现方法
  9. 京东进一步回应“承兴事件”:歌斐自身存在风控缺陷
  10. 深入AsyncTask
  11. Native Boot 从一个 VHD 引导系统的相关说明
  12. golang实现微信模板消息推送
  13. 使用 Litho 改进 News Feed 上的 Android 视频表现
  14. 公众号要如何排版?这几个必备公众号排版技巧千万不要错过哦
  15. 站内搜索引擎(ASP.NET)
  16. 计算机专业网名英语翻译,英语网名大全带翻译【三篇】
  17. Airdrop式社交:富友,你的airdrop没关
  18. 时光金科php_重庆金科博翠宸章 | ACA麦垦景观
  19. 计算机组成原理唐朔飞第六章知识点总结,计算机组成原理(唐朔飞)教材笔记 第六章 计算机的运算方法...
  20. 易语言人脸识别算法源码

热门文章

  1. C#的解题思路(1):不重复随机数的产生问题
  2. t-sql的执行顺序
  3. asp.net简单的投票系统代码 转载牛腩兄弟的
  4. 开发易于移植的J2ME游戏
  5. NLP(三) 预处理
  6. hdu1113 Word Amalgamation(详解--map和string的运用)
  7. saltstack 远程执行之返回写入到mysql
  8. python 连接sql server
  9. IIS出现 分析器错误消息: 在应用程序级别之外使用注册为 allowDefinition='MachineToApplication' 的节是错误的...
  10. node.js 学习