Bash: How to Compare a String with a Number


Often in Bash you may want to compare a string variable with a number.

You can use double brackets ( [[ ) with the following syntax to do so:

if [[ $num -gt 5 ]]
then
    echo "Number greater than 5"
else
    echo "Number not greater than 5"
fi

By using double brackets, we tell Bash that the text inside the brackets should be interpreted as an arithmetic expression.

This particular example checks if the number stored in the string variable named num is greater than 5 and returns one of the following strings as a result:

  • “Number greater than 5”
  • “Number not greater than 5”

Note that we use the -gt operator within the double brackets as “greater than” logic.

The following example shows how to use this syntax in practice.

Example: How to Compare a String with a Number in Bash

Suppose we create a variable named num with a value of “15” in Bash.

We can use the following syntax to check if this variable has a value greater than 5:

num="15"

if [[ $num -gt 5 ]]
then
    echo "Number greater than 5"
else
    echo "Number not greater than 5"
fi

The following screenshot shows how to use this syntax in practice:

Bash compare string with number

This returns “Number greater than 5” since the variable named num does indeed contain a value greater than 5.

Note that if you don’t need an else condition then you could use the following syntax instead:

num="15"

[[ $num -gt 5 ]] && echo "Number greater than 5"

This will only return output if the condition within the double brackets is met.

The following screenshot shows how to use this syntax in practice:

Bash compare string using double brackets

This returns “Number greater than 5” since the variable named num does indeed contain a value greater than 5.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Generate a Sequence of Numbers
Bash: How to Round Numbers to 2 Decimal Places
Bash: How to Check if Number is Even or Odd

Leave a Reply