What if...else
Let's take one of our previous and examine it in more detail:
#!/bin/bash
echo "Hello user, please give me a number between 10 and 20: "
read user_input
if [ ${user_input} -ge 10 ] && [ ${user_input} -le 20 ]
then
echo "Great! The number ${user_input} is what we were looking for!"
else
echo "The number ${user_input} is not what we are looking for..."
fi As an exercise to ease its comprehension, let's try to write it in natural language:
- Print a greeting asking for a number between 10 and 20
- Read the user input and save it in the
user_inputvariable - If the value of
user_inputis greater or equal to10and the value ofuser_inputis less or equal to2, then print an OK message to the user
- Otherwise (else), if the conditions are not met, print a not OK message
Fi, end of condition
These are the basics of a conditional statement and it lets you explore on condition: if it succeeds, an instruction is executed, if it fails, another block of instructions is invoked. We can...