Arithmetic operation



dos2unix

Well-Known Member
Credits
3,030
Not real sure what you are trying to do here.

let "SUM=5+5"
printf "%d" "$SUM"

let "SUM=$SUM-5"
printf "%d" "$SUM"

declare -i COST=4702
COST=\(COST+5\)/10*10
printf "%d\n" $COST

let "VAR=5 + 2"
printf "%d\n" "$VAR"

let "VAR=5 * 2"
printf "%d\n" "$VAR"

let "VAR=10 / 2"
printf "%d\n" "$VAR"

let "VAR=17 % 2"
printf "%d\n" "$VAR"

declare -i OCTAL=0
let "OCTAL=775"
printf "%i\n "$OCTAL"
 

JasKinasis

Well-Known Member
Credits
5,160
The shell can’t do floating point calculations.
If you need to use floating point you either need to use bc - which is a scriptable terminal based calculator.

Using bc:
Code:
echo "(1+2)/4" | bc -l
Or using variables:
Code:
echo "($a+$b)/$c" | bc -l
Or using variables and storing the result in a variable:
Code:
result=$(echo "($a+$b)/$c" | bc -l)
The -l flag causes bc to load a fixed precision library - so it’s not floating point per-se. If you don’t use the -l flag it will only perform integer mathematics.

Also, by default the precision is 20 decimal places. Which is more than enough precision for practical purposes.

But if you need more, or less precision, you can specify the number of decimal places like this:
Code:
result=$(echo "scale 2; ($a+$b)/$c" | bc -l)
Above should yield the result to 2 decimal places. Which might be more useful than 20 decimal places.

Alternatively, you could invoke something like the python interpreter to perform the calculation.

It doesn’t have to be python btw. It could be any other scripting language - Perl, ruby, lua etc... whatever “floats” your boat ha ha. I just mentioned python because it’s installed by default on most most, if not all modern distros.

Unfortunately, I don’t have time to put a python example together atm. But in your script, you can run your calculation through python, or some other interpreter.

If I get a chance later I might add a python example!
 

JasKinasis

Well-Known Member
Credits
5,160
There are two things wrong there:
1. Expr can only evaluate string or integer expressions.
2. Piping the result from expr to bc is pointless

In what you’ve posted, expr will evaluate the expression and then pass the result to bc. So in that example you’re getting an int result from expr. Piping that to bc is completely redundant, because it just gets passed the integer value from expr.

Ignore expr and just use bc.

The echo command in my bc examples creates an expression which is piped to bc for evaluation. bc evaluates the expression and displays/returns a fixed precision result!
 
Last edited:

Members online


Latest posts

Top