1
0
Fork 0
mirror of https://codeberg.org/Mo8it/How_To_Linux.git synced 2024-11-24 14:11:35 +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. 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 `[` 1. No space after `[`
```bash ```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" echo "VAR has the value 1"
fi fi
``` ```
1. No space before `==` and after `==`
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 `==`
```bash ```bash
if [ $VAR==1 ] if [ $VAR==1 ]
then then
@ -276,8 +266,42 @@ But the following snippets **work**:
fi 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 ### `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 -->
<!-- TODO: else if --> <!-- TODO: else if -->