Calculations in Bash
Doing calculations in Bash, is full of surprises. Like so many things in Bash or on Linux
What I am usually looking for:
$ echo $((1+1)) 2
Simple calculations - The problem
$ 1+1 bash: 1+1: command not found $ 1 + 1 bash: 1: command not found $ echo 1+1 1+1 $ echo (1+1) bash: syntax error near unexpected token `1+1' $ echo $(1+1) bash: 1+1: command not found $ echo $(1 + 1) bash: 1: command not found $(1+1) bash: 1+1: command not found $ expr 1+1 1+1 $ echo $((1+1)) 2 $ echo `expr 1 + 1` 2
Calculation + echo
Zie deze post voor diverse mogelijkheden. Het gaat mij hier om het retourneren van de uitkomst van een bewerking via echo
. Dat is van invloed op de mogelijkheden. Wat basically lijkt te werken:
echo $((1+1)) 2 echo `expr 1 + 1` 2
De eerste formulering met behulp van parenthesis command substitution is waarschijnlijk te prefereren: Command substitution (Bash).
Samengestelde berekeningen
$ echo $((12+1)) 13 $ echo $((12+1)*2) -bash: command substitution: line 1: syntax error near unexpected token `*2' -bash: command substitution: line 1: `(12+1)*2' $ echo $(((12+1)*2)) 26 $ a=12; b=1; echo $((a+b)) 13 $ a=12; b=1; c=2; echo $(((a+b)*c)) 26 $ a=12; b=1; c=2; echo $(((a+b)*c+1)) 27
Bestaande variabelen aanpassen
Bv.:
number_of_sites=29 echo $number_of_sites number_of_sites=$((number_of_sites-2)) echo $number_of_sites 29 27
Floating point arithmatic
Surprise: Bash can only handle integers!
Example: Conversion from mm to inch:
$ a=12; echo $((a*0.03937008)) bash: a*0.03937008: syntax error: invalid arithmetic operator (error token is ".03937008")
$ a=12; b=0.03937008; echo $a $b $((a*b)) bash: 0.03937008: syntax error: invalid arithmetic operator (error token is ".03937008")
However, there are lots of command line tools to take this job from Bash [1], with bc
being a commonly named tool, that seems to be part of a default Linux installation. I suspect it's name is an abbreviation of Bash Calculator.
See bc for details