mirror of
https://codeberg.org/Mo8it/How_To_Linux.git
synced 2024-11-24 12:01:36 +00:00
Add else block
This commit is contained in:
parent
afebcbabc1
commit
2cf045440d
1 changed files with 36 additions and 12 deletions
|
@ -227,7 +227,7 @@ In our first bash script, we check for equality of two variables with a double e
|
|||
|
||||
Speaking about syntax: You have to take spaces seriously with conditions.
|
||||
|
||||
For example, if we define the variable `VAR=1`, the following snippets **do not work**:
|
||||
For example, if we define the variable `VAR=1`, the following snippets **do not work** (or have an unexpected behavior):
|
||||
|
||||
1. No space after `[`
|
||||
```bash
|
||||
|
@ -258,17 +258,17 @@ For example, if we define the variable `VAR=1`, the following snippets **do not
|
|||
echo "VAR has the value 1"
|
||||
fi
|
||||
```
|
||||
|
||||
But the following snippets **work**:
|
||||
|
||||
1. Space after `[`, before `]`, before `==` and after `==`
|
||||
1. No space before `==` and after `==`
|
||||
```bash
|
||||
if [ $VAR==1 ]
|
||||
then
|
||||
echo "VAR has the value 1"
|
||||
fi
|
||||
```
|
||||
1. Space after `[` and before `]`. No space before `==` and after `==`
|
||||
|
||||
But the following snippet **work**:
|
||||
|
||||
- Space after `[`, before `]`, before `==` and after `==`
|
||||
```bash
|
||||
if [ $VAR == 1 ]
|
||||
then
|
||||
|
@ -278,6 +278,30 @@ But the following snippets **work**:
|
|||
|
||||
### `else` block
|
||||
|
||||
The `else` block runs commands inside it only if the condition is not true. The syntax is:
|
||||
|
||||
```bash
|
||||
if [ CONDITION ]
|
||||
then
|
||||
# Runs only if CONDITION is true
|
||||
(...)
|
||||
else
|
||||
# Runs only if CONDITION is false
|
||||
(...)
|
||||
fi
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
if [ $VAR == 1 ]
|
||||
then
|
||||
echo "VAR has the value 1"
|
||||
else
|
||||
echo "VAR does not have the value 1"
|
||||
fi
|
||||
```
|
||||
|
||||
<!-- TODO: else -->
|
||||
|
||||
<!-- TODO: else if -->
|
||||
|
|
Loading…
Reference in a new issue