EN
Bash - check if number is less than
0 points
In this article, we would like to show you how to check if number is less than another number in Bash.
In this example, we use -lt
operator to check if number is less than another number inside if
statement.
script.sh
file:
xxxxxxxxxx
1
2
3
number=3
4
5
if [ "$number" -lt 5 ]; then
6
echo "$number is less than 5"
7
fi
Note: this approach should be used in POSIX shells where other solutions may not work.
Run in command line:
xxxxxxxxxx
1
./script.sh
Output:
xxxxxxxxxx
1
3 is less than 5
xxxxxxxxxx
1
2
3
number=3
4
5
if test "$number" -lt 5; then
6
echo "$number is less than 5"
7
fi
Note:
[ ]
notation is shorthand oftest
command.
xxxxxxxxxx
1
2
3
number=3
4
5
if [[ "$number" -lt 5 ]]; then
6
echo "$number is less than 5"
7
fi
Note:
[[ ]]
notation is like extendedtest
command, adding additional features (e.g. regular expressions).
xxxxxxxxxx
1
2
3
number=3
4
5
if (( "$number" < 5 )); then
6
echo "$number is less than 5"
7
fi
Note:
(( ))
notation was created to simplyfy conditions (like in C language).