博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在Shell脚本中使用if-else?
阅读量:2533 次
发布时间:2019-05-11

本文共 7850 字,大约阅读时间需要 26 分钟。

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

从上一章有关教程开始,让我们了解如何在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]then   statement1else   statement2fi

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/bashm=1n=2if [ $n -eq $m ]then        echo "Both variables are the same"else        echo "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/basha=2b=7if [ $a -ge $b ]then  echo "The variable 'a' is greater than the variable 'b'."else  echo "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/bashn=10if [ $((n%2))==0 ]then  echo "The number is even."else  echo "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/bashecho "Enter password"read passif [ $pass="password" ]then  echo "The password is correct."else  echo "The password is incorrect, try again."fi
Bash Password
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函数。 如果您有任何疑问,反馈或建议,请随时通过以下评论与我们联系。

翻译自:

转载地址:http://uqlzd.baihongyu.com/

你可能感兴趣的文章
feign调用spring clound eureka 注册中心服务
查看>>
ZT:Linux上安装JDK,最准确
查看>>
LimeJS指南3
查看>>
关于C++ const成员的一些细节
查看>>
《代码大全》学习摘要(五)软件构建中的设计(下)
查看>>
C#检测驱动是否安装的问题
查看>>
web-4. 装饰页面的图像
查看>>
微信测试账户
查看>>
Android ListView上拉获取下一页
查看>>
算法练习题
查看>>
学习使用Django一 安装虚拟环境
查看>>
Hibernate视频学习笔记(8)Lazy策略
查看>>
CSS3 结构性伪类选择器(1)
查看>>
IOS 杂笔-14(被人遗忘的owner)
查看>>
自动测试用工具
查看>>
前端基础之BOM和DOM
查看>>
[T-ARA/筷子兄弟][Little Apple]
查看>>
编译Libgdiplus遇到的问题
查看>>
【NOIP 模拟赛】Evensgn 剪树枝 树形dp
查看>>
java学习笔记④MySql数据库--01/02 database table 数据的增删改
查看>>