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.
Practical example
In this example, we use -eq equality operator to compare two numbers inside if statement.
script.sh file:
#!/bin/bash
number=5
if [ "$number" -eq 5 ]; then
echo "The numbers are equal."
fi
Run in command line:
./script.sh
Output:
The numbers are equal.
Altermative notation
1. test based solution
#!/bin/bash
number=5
if test "$number" -eq 5; then
echo "The numbers are equal."
fi
Note:
[ ]notation is shorthand oftestcommand.
2. [[ ]] based solution
#!/bin/bash
number=5
if [[ "$number" -eq 5 ]]; then
echo "The numbers are equal."
fi
Note:
[[ ]]notation is like extendedtestcommand.
3. (( )) based solution
#!/bin/bash
number=5
if (( "$number" == 5 )); then
echo "The numbers are equal."
fi
Note:
(( ))notation was created to simplyfy conditions.
Possible operators
test, [ ], or [[ ]] | (( )) | Description |
|---|---|---|
-eq | == | Equal |
-ne | != | Not equal |
-lt | < | Less than |
-le | <= | Less than or equal |
-gt | > | Greater than |
-ge | >= | Greater than or equal |