I am having troubles with the arithmetic expressions in a bash file (a unix file .sh).
I have the variable "total", which consists of a few numbers separated by spaces, and I want to calculate the sum of them (in the variable "dollar").
#!/bin/bash
..
dollar=0
for a in $total; do
$dollar+=$a
done
I know I am missing something with the arithmetic brackets, but I couldn't get it to work with variables.
There are a number of ways to perform arithmetic in Bash. Some of them are:
dollar=$((dollar + a)) # modern: in-process, POSIX-defined
((dollar += a)) # modern: in-process, non-POSIX bash extension
dollar=$(expr "$dollar" + "$a") # legacy: out-of-process, slow, POSIX-defined
let "dollar += $a" # legacy: in-process, pre-POSIX ksh syntax
You may see more on the wiki. If you need to handle non-integer values, use a external tool such as bc.
Wrap arithmetic operations within ((...)):
dollar=0
for a in $total; do
((dollar += a))
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With