Languages
[Edit]
EN

Bash - compare number variable to another number

3 points
Created by:
Hiba-Tate
548

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 of test command.

2. [[ ]] based solution

#!/bin/bash

number=5

if [[ "$number" -eq 5 ]]; then
    echo "The numbers are equal."
fi

Note: [[ ]] notation is like extended test command.

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

 

See also

  1. Bash - compare string variable to another string

Alternative titles

  1. Bash - compare numbers
  2. Bash - compare number to another number value
  3. Bash - two numbers comparison
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join