1
0
Fork 0
mirror of https://codeberg.org/Mo8it/How_To_Linux.git synced 2024-10-18 11:52:39 +00:00

Add else block

This commit is contained in:
Mo 2022-09-26 21:11:21 +02:00
parent afebcbabc1
commit 2cf045440d

View file

@ -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,7 @@ 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 `==`
```bash
if [ $VAR == 1 ]
then
echo "VAR has the value 1"
fi
```
1. Space after `[` and before `]`. No space before `==` and after `==`
1. No space before `==` and after `==`
```bash
if [ $VAR==1 ]
then
@ -276,8 +266,42 @@ But the following snippets **work**:
fi
```
But the following snippet **work**:
- Space after `[`, before `]`, before `==` and after `==`
```bash
if [ $VAR == 1 ]
then
echo "VAR has the value 1"
fi
```
### `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 -->