1

Suppose we have a file like 'abc.txt' which has a single value 123456 and file 'xyz.txt' which also has a single value like 654321. I want to store these values form the file to some shell variable like abc = 123456 and xyz = 654321 and wanted to do some operations like density=$abc/$xyz. I am able to transfer the contents form the file to variables but it is not treating contents of shell variables like numbers on which we can do arithmetic. What can be done for this?

How to do integer & float calculations, in bash or other languages/frameworks? link has helped various ways to do arithmetic but did not tell about the values from the file assigned to variable will be eligible for arithmetic or not?

2 Answers2

1

If you are using the Bash shell:

#!/bin/bash
abc=$(<abc.txt)
xyz=$(<xyz.txt)
density=$((abc / xyz))
echo "$density"

Note: Output will be 0 for this because numerator is less than denominator.

serenesat
  • 1,326
0

Shell arithmetics is integer only. Use bc for that:

echo $var1/$var2 | bc -l

or the simpler

bc -l <<< $var1/$var2
FelixJN
  • 13,566
  • What should be done if we want floating point arithmetic to be done using shell variables. Please answer me, I am stuck in somewhere very critical issues. – user127956 Aug 10 '15 at 09:56