EN
Bash - compare number variable to another number
3 points
In this article, we would like to show you how to compare number variable to another number in Bash.
In this example, we use -eq
equality operator to compare two numbers inside if
statement.
script.sh
file:
xxxxxxxxxx
1
2
3
number=5
4
5
if [ "$number" -eq 5 ]; then
6
echo "The numbers are equal."
7
fi
Run in command line:
xxxxxxxxxx
1
./script.sh
Output:
xxxxxxxxxx
1
The numbers are equal.
xxxxxxxxxx
1
2
3
number=5
4
5
if test "$number" -eq 5; then
6
echo "The numbers are equal."
7
fi
Note:
[ ]
notation is shorthand oftest
command.
xxxxxxxxxx
1
2
3
number=5
4
5
if [[ "$number" -eq 5 ]]; then
6
echo "The numbers are equal."
7
fi
Note:
[[ ]]
notation is like extendedtest
command.
xxxxxxxxxx
1
2
3
number=5
4
5
if (( "$number" == 5 )); then
6
echo "The numbers are equal."
7
fi
Note:
(( ))
notation was created to simplyfy conditions.
test , [ ] , or [[ ]] | (( )) | Description |
---|---|---|
-eq | == | Equal |
-ne | != | Not equal |
-lt | < | Less than |
-le | <= | Less than or equal |
-gt | > | Greater than |
-ge | >= | Greater than or equal |