EN
Bash - check if number is less or equal
0
points
In this article, we would like to show you how to check if number is less or equal to another number in Bash.
Practical example
In this example, we use -le operator to check if number is less or equal to another number inside if statement.
script.sh file:
#!/bin/bash
number=3
if [ "$number" -le 5 ]; then
echo "$number is less or equal to 5"
fi
Note: this approach should be used in POSIX shells where other solutions may not work.
Run in command line:
./script.sh
Output:
3 is less or equal to 5
Altermative notation
1. test based solution
#!/bin/bash
number=3
if test "$number" -le 5; then
echo "$number is less or equal to 5"
fi
Note:
[ ]notation is shorthand oftestcommand.
2. [[ ]] based solution
#!/bin/bash
number=3
if [[ "$number" -le 5 ]]; then
echo "$number is less or equal to 5"
fi
Note:
[[ ]]notation is like extendedtestcommand, adding additional features (e.g. regular expressions).
3. (( )) based solution
#!/bin/bash
number=3
if (( "$number" <= 5 )); then
echo "$number is less or equal to 5"
fi
Note:
(( ))notation was created to simplyfy conditions (like in C language).