Calculations in Bash
Versie door Jeroen Strompf (overleg | bijdragen) op 9 jun 2022 om 06:08
Rekenen met variabelen in Bash - Bourne Again Shell op Linux, gaat niet zo vanzelfsprekend als verwacht:
Het probleem
Zie hier mijn afdaling in het konijnenhol, of de afgrond - Wat je het meeste aanspreekt:
$ 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
Sommetje + 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