6

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.

4

2 Answers 2

9

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

dollar=0
for a in $total; do
  ((dollar += a))
done
Sign up to request clarification or add additional context in comments.

Comments

8

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.