if statement
When using if-statements, we are already aware that a check is made where an operator is used to determine how we proceed with the execution.
#if
A very common if-statement. Please enjoy.
#!/usr/bin/env bash
#
# An example script on if statement
# If with values
val1=10
if [[ $val1 -gt 5 ]]
then
echo "$val1 is greater than 5"
fi
# If with strings
string1="music"
string2="acoustic"
if [[ $string1 = "music" ]]
then
echo "$string1 spells like music"
fi
if [[ $string1 != "$string2" ]]
then
echo "$string1 is not the same word as $string2"
fi
#else-if/else
We mix the else-if and else blocks and look at what the design looks like:
#!/usr/bin/env bash
#
# An example script on if/else-if statement
# If/else-if/else with values
val1=5
if [[ $val1 -gt 5 ]]
then
echo "$val1 is greater than 5"
elif [[ $val1 -lt 5 ]]
then
echo "$val1 is less than 5"
else
echo "$val1 is 5"
fi
You can also come across constructions like:
#!/usr/bin/env bash
#
# An example script on if/else-if statement
# If/else-if/else with values
val1=5
if [[ $val1 -gt 5 ]]; then echo "$val1 is greater than 5"
elif [[ $val1 -lt 5 ]]; then echo "$val1 is less than 5"
else echo "$val1 is 5"
fi
It works just as well and validates nicely. The semicolon is used to separate commands on the same row.
#Ternary
Many of you are probably wondering if it can be shortened even more, like a ternary operator. We solve it as follows:
#!/usr/bin/env bash
#
# An example script on ternary variant
val1=10
[[ $val1 -ge 5 ]] && res="greater or equal" || res="less"
echo "$res"
#Revision history
- 2019-08-19: (A, lew) First edition.