Skip to content

Commit 751a8e6

Browse files
authored
Multiple conditions (bobbyiliev#34)
* Add multiple conditions example
1 parent 81756aa commit 751a8e6

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

ebook/en/content/010-bash-conditionals.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,24 @@ fi
7878

7979
If you put this on top of your script it would exit in case that the EUID is 0 and would not execute the rest of the script. This was discussed on [the DigitalOcean community forum](https://www.digitalocean.com/community/questions/how-to-check-if-running-as-root-in-a-bash-script).
8080

81+
You can also test multiple conditions with an `if` statement. In this example we want to make sure that the user is neither the admin user or the root user to ensure the script is incapable of causing too much damage. We'll use the `or` operator in this example, noted by `||`. This means that either of the conditions needs to be true. If we used the `and` operator of `&&` then both conditions would need to be true.
82+
83+
```bash
84+
#!/bin/bash
85+
86+
admin="devdojo"
87+
88+
read -p "Enter your username? " username
89+
90+
# Check if the username provided is the admin
91+
92+
if [[ "${username}" != "${admin}" ]] || [[ $EUID != 0 ]] ; then
93+
echo "You are not the admin or root user, but please be safe!"
94+
else
95+
echo "You are the admin user! This could be very destructive!"
96+
fi
97+
```
98+
8199
## Switch case statements
82100

83101
As in other programming languages, you can use a `case` statement to simplify complex conditionals when there are multiple different choices. So rather than using a few `if`, and `if-else` statements, you could use a single `case` statement.

0 commit comments

Comments
 (0)