Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash arithmetic expressions with variables

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.

like image 248
sheldonzy Avatar asked Aug 27 '26 19:08

sheldonzy


2 Answers

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.

like image 50
ephemient Avatar answered Aug 30 '26 09:08

ephemient


Wrap arithmetic operations within ((...)):

dollar=0
for a in $total; do
  ((dollar += a))
done
like image 29
janos Avatar answered Aug 30 '26 09:08

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!