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.
CodePudding user response:
You can use arithmetic context ((..))
:
num=1
declare -A array
((array[0] =$num))
((array[0] =$num))
echo ${array[0]}
2
CodePudding user response:
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.