EanderAlx.org

Linux, Virtualization and whatever I find interesting ...

User Tools


Site Tools


bashscr:calculate

Calculate in bash

  • If you want to calculate with an integer it's possible without using other programs.

  • For example 34+23=57
COUNT1="34"
COUNT2="23"
echo $[$COUNT1 + $COUNT2]
  • If you want to move the decimal point one digit to the left than you will have to use modulo.
  • For example 34/10=3.4
COUNT1="34"
COUNT2="10"
echo "$[$COUNT1 / $COUNT2].$[$COUNT1 % $COUNT2]"
  • To calculate with float or more complex thing use “bc”
echo "2.5 + 3.2" | bc -l
5.7
  • If you want to cut digits after the decimal point you can use scale (It's no rounding like you see in the example)
echo "scale = 4; 2.5 / 1.9 " | bc -l 
1.3157
echo "scale = 2; 2.5 / 1.9 " | bc -l 
1.31
  • The remaining Problem is:
echo "scale = 2; 2.5 / 3.1 " | bc -l 
.8064
  • The leading zero is lost
  • You can search and replace using “sed”
echo "scale = 3; 2.5 / 3.1 " | bc -l | sed -r 's/^\./0./g'
0.806
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
bashscr/calculate.txt · Last modified: 23.03.2013 18:24 by eanderalx