2

I'm learning shall scripting, and I wonder if there's any way to add numbers to an element of an array so that the number would be added to the element instead of appending it.

num=1
declare -A array
array[0]+=$num
array[0]+=$num
echo ${array[0]}

obviously, the result would be '11' instead of 2. I know this question might exists in the community, but I couldn't find it maybe because I don't know how to name the problem.

2 Answers 2

3

You can use arithmetic context ((..)):

num=1
declare -A array
((array[0]+=$num))
((array[0]+=$num))
echo ${array[0]}

2
Sign up to request clarification or add additional context in comments.

Comments

2

Giving the array the integer attribute enables "bare" arithmetic:

num=1
declare -Ai array
array[0]+=$num         
array[0]+=num        # also works without expanding the variable
                     # because this is arithmetic evaluation
declare -p array

outputs

declare -Ai array=([0]="2" )

-A defines an associative array. -i also works with -a numerically-indexed arrays.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.