Mike D
Mike D

Reputation: 365

Bash: display all instances of negative numbers as zero

After some math, I'd like to display all occurrences of negative numbers as zero instead. Simple example:

num1=6
num2=8
firstresult=$(( $num1 - $num2 ))
echo $result
#
num3=2
num4=9
secondresult=$(( $num3 - $num4 ))
echo $secondresult

so on... both result variables will yield a negative number, obviously. I'd like those numbers to display as zeros.

Maybe some function to write? Not sure. Any help is appreciated.

Upvotes: 3

Views: 838

Answers (1)

glenn jackman
glenn jackman

Reputation: 247012

no_negatives () {
    echo "$(( $1 < 0 ? 0 : $1 ))"
}

That's a pretty crummy name, feel free to pick a better one. Then:

$ a=5 b=3
$ no_negatives $((a - b))
2
$ no_negatives $((b - a))
0

Upvotes: 7

Related Questions