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
Related Posts
- How to measure elapsed time in Bash
- Ceil, Floor, Round off a devided number in Bash
- Check if a number is Positive or Negative in Bash
- How to Print a Variable in Bash
- Number Comparison Operators in Bash
- Convert between Uppercase and Lowercase in Bash
- Check if a File or Directory exists in Bash
- How to extract substring in Bash
- Bash Case Statement with examples
- How to use Command Line Arguments in Bash
- How to use Arrays in Bash
- How to Compare strings in Bash Shell
- if..else statement in Bash
- Add, Subtract, Multiply, Division with Numbers in Bash
- Bash For, Whlie Loop Examples
- How to Pass and Use command line arguments in Bash