mirror of
https://github.com/LCTT/TranslateProject.git
synced 2025-03-21 02:10:11 +08:00
commit
696a7d655f
@ -1,214 +0,0 @@
|
||||
[#]: subject: "Bash Basics Series #7: If Else Statement"
|
||||
[#]: via: "https://itsfoss.com/bash-if-else/"
|
||||
[#]: author: "Abhishek Prakash https://itsfoss.com/author/abhishek/"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: "geekpi"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
Bash Basics Series #7: If Else Statement
|
||||
======
|
||||
|
||||
Bash supports if-else statements so that you can use logical reasoning in your shell scripts.
|
||||
|
||||
The generic if-else syntax is like this:
|
||||
|
||||
```
|
||||
if [ expression ]; then
|
||||
|
||||
## execute this block if condition is true else go to next
|
||||
|
||||
elif [ expression ]; then
|
||||
|
||||
## execute this block if condition is true else go to next
|
||||
|
||||
else
|
||||
|
||||
## if none of the above conditions are true, execute this block
|
||||
|
||||
fi
|
||||
```
|
||||
|
||||
As you can notice:
|
||||
|
||||
- `elif` is used for "else if" kind of condition
|
||||
- The if else conditions always end with `fi`
|
||||
- the use of semicolon `;` and `then` keyword
|
||||
|
||||
Before I show the examples of if and else-if, let me share common comparison expressions (also called test conditions) first.
|
||||
|
||||
### Test conditions
|
||||
|
||||
Here are the test condition operators you can use for numeric comparison:
|
||||
|
||||
| Condition | Equivalent to true when |
|
||||
| :- | :- |
|
||||
| $a -lt $b | $a < $b ($a is **l**ess **t**han $b) |
|
||||
| $a -gt $b | $a > $b ($a is **g**reater **t**han $b) |
|
||||
| $a -le $b | $a <= $b ($a is **l**ess or **e**qual than $b) |
|
||||
| $a -ge $b | $a >= $b ($a is **g**reater or **e**qual than $b) |
|
||||
| $a -eq $b | $a is equal to $b |
|
||||
| $a -ne $b | $a is not equal to $b |
|
||||
|
||||
If you are comparing strings, you can use these test conditions:
|
||||
|
||||
| Condition | Equivalent to true when |
|
||||
| :- | :- |
|
||||
| "$a" = "$b" | $a is same as $b |
|
||||
| "$a" == "$b" | $a is same as $b |
|
||||
| "$a" != "$b" | $a is different from $b |
|
||||
| -z "$a" | $a is empty |
|
||||
|
||||
There are also conditions for file type check:
|
||||
|
||||
| Condition | Equivalent to true when |
|
||||
| :- | :- |
|
||||
| -f $a | $a is a file |
|
||||
| -d $a | $a is a directory |
|
||||
| -L $a | $a is a link |
|
||||
|
||||
Now that you are aware of the various comparison expressions let's see them in action in various examples.
|
||||
|
||||
### Use if statement in bash
|
||||
|
||||
Let's create a script that tells you if a given number is even or not.
|
||||
|
||||
Here's my script named `even.sh`:
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
read -p "Enter the number: " num
|
||||
|
||||
mod=$(($num%2))
|
||||
|
||||
if [ $mod -eq 0 ]; then
|
||||
echo "Number $num is even"
|
||||
fi
|
||||
```
|
||||
|
||||
The modulus operation (%) returns zero when it is perfectly divided by the given number (2 in this case).
|
||||
|
||||
> 🚧 Pay special attention to space. There must be space between the opening and closing brackets and the conditions. Similarly, space must be before and after the conditional operators (-le, == etc).
|
||||
|
||||
Here's what it shows when I run the script:
|
||||
|
||||
![Running a script with if statement example in bash][1]
|
||||
|
||||
Did you notice that the script tells you when a number is even but it doesn't display anything when the number is odd? Let's improve this script with the use of else.
|
||||
|
||||
### Use if else statement
|
||||
|
||||
Now I add an else statement in the previous script. This way when you get a non-zero modulus (as odd numbers are not divided by 2), it will enter the else block.
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
read -p "Enter the number: " num
|
||||
|
||||
mod=$(($num%2))
|
||||
|
||||
if [ $mod -eq 0 ]; then
|
||||
echo "Number $num is even"
|
||||
else
|
||||
echo "Number $num is odd"
|
||||
fi
|
||||
```
|
||||
|
||||
Let's run it again with the same numbers:
|
||||
|
||||
![Running a bash script that checks odd even number][2]
|
||||
|
||||
As you can see, the script is better as it also tells you if the number is odd.
|
||||
|
||||
### Use elif (else if) statement
|
||||
|
||||
Here's a script that checks whether the given number is positive or negative. In mathematics, 0 is neither positive nor negative. This script keeps that fact in check as well.
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
read -p "Enter the number: " num
|
||||
|
||||
if [ $num -lt 0 ]; then
|
||||
echo "Number $num is negative"
|
||||
elif [ $num -gt 0 ]; then
|
||||
echo "Number $num is positive"
|
||||
else
|
||||
echo "Number $num is zero"
|
||||
fi
|
||||
```
|
||||
|
||||
Let me run it to cover all three cases here:
|
||||
|
||||
![Running a script with bash elif statement][3]
|
||||
|
||||
### Combine multiple conditions with logical operators
|
||||
|
||||
So far, so good. But do you know that you may have multiple conditions in a single by using logical operators like AND (&&), OR (||) etc? It gives you the ability to write complex conditions.
|
||||
|
||||
Let's write a script that tells you whether the given year is a leap year or not.
|
||||
|
||||
Do you remember the conditions for being a leap year? It should be divided by 4 but if it is divisible by 100, it's not a leap year. However, if it is divisible by 400, it is a leap year.
|
||||
|
||||
Here's my script.
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
read -p "Enter the year: " year
|
||||
|
||||
if [[ ($(($year%4)) -eq 0 && $(($year%100)) != 0) || ($(($year%400)) -eq 0) ]]; then
|
||||
echo "Year $year is leap year"
|
||||
else
|
||||
echo "Year $year is normal year"
|
||||
fi
|
||||
```
|
||||
|
||||
> 💡 Notice the use of double brackets [[ ]] above. It is mandatory if you are using logical operators.
|
||||
|
||||
Verify the script by running it with different data:
|
||||
|
||||
![Example of running bash script with logical operators in if statement][4]
|
||||
|
||||
### 🏋️ Exercise time
|
||||
|
||||
Let's do some workout :)
|
||||
|
||||
**Exercise 1**: Write a bash shell script that checks the length of the string provided to it as an argument. If no argument is provided, it prints 'empty string'.
|
||||
|
||||
**Exercise 2**: Write a shell script that checks whether a given file exists or not. You can provide the full file path as the argument or use it directly in the script.
|
||||
|
||||
**Hint**: Use -f for file
|
||||
|
||||
**Exercise 3**: Enhance the previous script by checking if the given file is regular file, a directory or a link or if it doesn't exist.
|
||||
|
||||
**Hint**: Use -f, -d and -L
|
||||
|
||||
**Exercise 3**: Write a script that accepts two string arguments. The script should check if the first string contains the second argument as a substring.
|
||||
|
||||
**Hint**: Refer to the previous chapter on [bash strings][5]
|
||||
|
||||
You may discuss your solution in the Community:
|
||||
|
||||
I hope you are enjoying the Bash Basics Series. In the next chapter, you'll learn about using loops in Bash. Keep on bashing!
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://itsfoss.com/bash-if-else/
|
||||
|
||||
作者:[Abhishek Prakash][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://itsfoss.com/author/abhishek/
|
||||
[b]: https://github.com/lkxed/
|
||||
[1]: https://itsfoss.com/content/images/2023/07/bash-if-example.png
|
||||
[2]: https://itsfoss.com/content/images/2023/07/bash-if-else-example.png
|
||||
[3]: https://itsfoss.com/content/images/2023/07/bash-elif.png
|
||||
[4]: https://itsfoss.com/content/images/2023/07/bash-logical-operators-in-if-else.png
|
||||
[5]: https://itsfoss.com/bash-strings/
|
@ -0,0 +1,217 @@
|
||||
[#]: subject: "Bash Basics Series #7: If Else Statement"
|
||||
[#]: via: "https://itsfoss.com/bash-if-else/"
|
||||
[#]: author: "Abhishek Prakash https://itsfoss.com/author/abhishek/"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: "geekpi"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
Bash 基础知识系列 #7:If Else 语句
|
||||
======
|
||||
|
||||
Bash 支持 if-else 语句,以便你可以在 shell 脚本中使用逻辑推理。
|
||||
|
||||
通用的 if-else 语法如下:
|
||||
|
||||
```
|
||||
if [ expression ]; then
|
||||
|
||||
## 如果条件为真则执行此块,否则转到下一个
|
||||
|
||||
elif [ expression ]; then
|
||||
|
||||
## 如果条件为真则执行此块,否则转到下一个
|
||||
|
||||
else
|
||||
|
||||
## 如果以上条件都不成立,则执行此块
|
||||
|
||||
fi
|
||||
```
|
||||
|
||||
正如你所注意到的:
|
||||
|
||||
- `elif` 用于 “else if” 类型的条件。
|
||||
- if else 条件始终以 `fi` 结尾。
|
||||
- 使用分号 `;`和 `then`关键字
|
||||
|
||||
在展示 if 和 else-if 的示例之前,我先分享一下常见的比较表达式(也称为测试条件)。
|
||||
|
||||
### 测试条件
|
||||
|
||||
以下是可用于数字比较的测试条件运算符:
|
||||
|
||||
| 条件 | 当满足以下条件时为 true |
|
||||
| :-| :-|
|
||||
| $a -lt $b | $a < $b($a 是 **小于** $b)|
|
||||
| $a -gt $b | $a > $b($a 是 **大于** $b)|
|
||||
| $a -le $b | $a <= $b($a **小于等于** $b )|
|
||||
| $a -ge $b | $a >= $b ($a **大于等于** $b)
|
||||
| $a -eq $b | $a 等于 $b |
|
||||
| $a -ne $b | $a 不等于 $b |
|
||||
|
||||
如果你要比较字符串,可以使用以下测试条件:
|
||||
|
||||
| 条件 | 当满足以下条件时为 true |
|
||||
| :- | :- |
|
||||
| “$a”=“$b”| $a 与 $b 相同 |
|
||||
| “$a”==“$b”| $a 与 $b 相同 |
|
||||
| “$a”!=“$b”| $a 与 $b 不同 |
|
||||
| -z“$a”| $a 为空 |
|
||||
|
||||
文件类型检查也有条件:
|
||||
|
||||
| 条件 | 当满足以下条件时为 true |
|
||||
| :- | :- |
|
||||
| -f $a | $a 是一个文件 |
|
||||
| -d $a | $a 是一个目录 |
|
||||
| -L $a | $a 是一个链接 |
|
||||
|
||||
现在你已经了解了各种比较表达式,让我们在各种示例中看看它们的实际应用。
|
||||
|
||||
### 在 bash 中使用 if 语句
|
||||
|
||||
让我们创建一个脚本来告诉你给定的数字是否为偶数。
|
||||
|
||||
这是我的脚本,名为 `even.sh`:
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
read -p "Enter the number: " num
|
||||
|
||||
mod=$(($num%2))
|
||||
|
||||
if [ $mod -eq 0 ]; then
|
||||
echo "Number $num is even"
|
||||
fi
|
||||
```
|
||||
|
||||
当模数运算 (%) 整除给定数字(本例中为 2)时,它返回零。
|
||||
|
||||
> 🚧 特别注意空格。左括号和右括号与条件之间必须有空格。同样,条件运算符(-le、== 等)前后必须有空格。
|
||||
|
||||
这是我运行脚本时显示的内容:
|
||||
|
||||
![Running a script with if statement example in bash][1]
|
||||
|
||||
你是否注意到,当数字为偶数时,脚本会告诉你,但当数字为奇数时,脚本不会显示任何内容? 让我们使用 else 来改进这个脚本。
|
||||
|
||||
### 使用 if else 语句
|
||||
|
||||
现在我在前面的脚本中添加了一条 else 语句。这样,当你得到一个非零模数(因为奇数不能除以 2)时,它将进入 else 块。
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
read -p "Enter the number: " num
|
||||
|
||||
mod=$(($num%2))
|
||||
|
||||
if [ $mod -eq 0 ]; then
|
||||
echo "Number $num is even"
|
||||
else
|
||||
echo "Number $num is odd"
|
||||
fi
|
||||
```
|
||||
|
||||
让我们用相同的数字再次运行它:
|
||||
|
||||
![Running a bash script that checks odd even number][2]
|
||||
|
||||
正如你所看到的,该脚本更好,因为它还告诉你该数字是否为奇数。
|
||||
|
||||
### 使用 elif(else if)语句
|
||||
|
||||
这是一个检查给定数字是正数还是负数的脚本。在数学中,0 既不是正数也不是负数。该脚本也检查了这一事实。
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
read -p "Enter the number: " num
|
||||
|
||||
if [ $num -lt 0 ]; then
|
||||
echo "Number $num is negative"
|
||||
elif [ $num -gt 0 ]; then
|
||||
echo "Number $num is positive"
|
||||
else
|
||||
echo "Number $num is zero"
|
||||
fi
|
||||
```
|
||||
|
||||
让我运行它来涵盖这里的所有三种情况:
|
||||
|
||||
![Running a script with bash elif statement][3]
|
||||
|
||||
### 用逻辑运算符组合多个条件
|
||||
|
||||
到目前为止,一切都很好。但是你是否知道通过使用 AND (&&)、OR (||) 等逻辑运算符可以在一个条件中包含多个条件? 它使你能够编写复杂的条件。
|
||||
|
||||
让我们编写一个脚本来告诉你给定的年份是否是闰年。
|
||||
|
||||
你还记得闰年的条件吗? 它应该被 4 整除,但如果它能被 100 整除,那么它就不是闰年。但是,如果能被 400 整除,则为闰年。
|
||||
|
||||
这是我的脚本。
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
read -p "Enter the year: " year
|
||||
|
||||
if [[ ($(($year%4)) -eq 0 && $(($year%100)) != 0) || ($(($year%400)) -eq 0) ]]; then
|
||||
echo "Year $year is leap year"
|
||||
else
|
||||
echo "Year $year is normal year"
|
||||
fi
|
||||
```
|
||||
|
||||
> 💡 注意上面双括号 [[ ]] 的使用。如果你使用逻辑运算符,则这是强制性的。
|
||||
|
||||
通过使用不同的数据运行脚本来验证脚本:
|
||||
|
||||
![Example of running bash script with logical operators in if statement][4]
|
||||
|
||||
### 🏋️ 练习时间
|
||||
|
||||
让我们做一些练习吧 :)
|
||||
|
||||
**练习 1**:编写一个 bash shell 脚本,检查作为参数提供给它的字符串的长度。如果未提供参数,它将打印 “empty string”。
|
||||
|
||||
**练习 2**:编写一个 shell 脚本来检查给定文件是否存在。你可以提供完整的文件路径作为参数或直接在脚本中使用它。
|
||||
|
||||
**提示**:文件使用 -f 选项
|
||||
|
||||
**练习 3**:通过检查给定文件是否是常规文件、目录或链接或者是否不存在来增强之前的脚本。
|
||||
|
||||
**提示**:使用 -f、-d 和 -L
|
||||
|
||||
**练习 3**:编写一个接受两个字符串参数的脚本。脚本应检查第一个字符串是否包含第二个参数的子串。
|
||||
|
||||
**提示**:请参阅上一章 [bash 字符串][5]
|
||||
|
||||
你可以在社区中讨论你的解决方案:
|
||||
|
||||
[Bash 基础系列练习 #7:If Else 语句][6]
|
||||
|
||||
我希望你喜欢 Bash 基础知识系列。在下一章中,你将了解如何在 Bash 中使用循环。继续编写 bash!
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://itsfoss.com/bash-if-else/
|
||||
|
||||
作者:[Abhishek Prakash][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[geekpi](https://github.com/geekpi)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://itsfoss.com/author/abhishek/
|
||||
[b]: https://github.com/lkxed/
|
||||
[1]: https://itsfoss.com/content/images/2023/07/bash-if-example.png
|
||||
[2]: https://itsfoss.com/content/images/2023/07/bash-if-else-example.png
|
||||
[3]: https://itsfoss.com/content/images/2023/07/bash-elif.png
|
||||
[4]: https://itsfoss.com/content/images/2023/07/bash-logical-operators-in-if-else.png
|
||||
[5]: https://itsfoss.com/bash-strings/
|
||||
[6]: https://itsfoss.community/t/practice-exercise-in-bash-basics-series-7-if-else-statements/10926?ref=itsfoss.com
|
Loading…
Reference in New Issue
Block a user