Check if a number is Positive or Negative in Bash

This article will introduce how to check if a number is Positive or Negative in Bash.

1. Example (1)

We can determine whether a number is positive or negative using a if statement.

The -lt in the if statement means less than and compares if it is less than 0. Also, -gt means greater than and compares if it is greater than 0 in the if statement.

#!/bin/bash

checkNumber() {
    num=$1

    if [ $num -lt 0 ]
    then
        echo "Negative:" "$num"
    elif [ $num -gt 0 ]
    then
        echo "Positive:" "$num"
    else
        echo "The number is 0:" "$num"
    fi
}

checkNumber 10
checkNumber -10
checkNumber 0

Output:

$ bash example.sh
Positive: 10
Negative: -10
The number is 0: 0

If you would like to know more about operators such as -lt and -gt, please refer to Number Comparison Operators.

1. Example (2)

In this example, the if statement was implemented using > or < instead of -gt or -lt.

#!/bin/bash

checkNumber() {
    num=$1

    if (("$num" < 0 ))
    then
        echo "Negative:" "$num"
    elif (("$num" > 0 ))
    then
        echo "Positive:" "$num"
    else
        echo "The number is 0:" "$num"
    fi
}

checkNumber 10
checkNumber -10
checkNumber 0

Output:

$ bash example.sh
Positive: 10
Negative: -10
The number is 0: 0
codechachaCopyright ©2019 codechacha