Performing Integer Math with Integer Variables
Instead of using mathematical expressions, you can use integer variables.
You’ve already seen the kind of thing that doesn’t work, which looks like this:
[donnie@fedora ~]$ a=1
[donnie@fedora ~]$ b=2
[donnie@fedora ~]$ echo $a + $b
1 + 2
[donnie@fedora ~]$
That’s because by default, the values of variables are text strings, rather than numbers. To make this work, use the declare -i
command to create integer variables, like this:
[donnie@fedora ~]$ declare -i a=1
[donnie@fedora ~]$ declare -i b=2
[donnie@fedora ~]$ declare -i result=a+b
[donnie@fedora ~]$ echo $result
3
[donnie@fedora ~]$
Here’s how it look in the math5.sh
script:
#!/bin/bash
declare -i val1=$1
declare -i val2=$2
declare -i result1=val1+val2
declare -i result2=val1/val2
declare -i result3=val1*val2
declare -i result4=val1-val2
declare -i result5=val1%val2
echo "Addition: $result1"
echo "Division: $result2...