Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic operation on all elements in BASH array

Say we have a BASH array with integers:

declare -a arr=( 1 2 3 )

and I want to do an arithmetic operation on each element, e.g. add 1. Is there an altenative to a for loop:

for (( i=0 ; i<=${#arr[@]}-1 ; i++ )) ; do
    arr[$i]=$(( ${arr[$i]} + 1 ))
done

I have tried a few options:

arr=$(( ${arr[@]} + 1 ))

fails, while

arr=$(( $arr + 1 ))

results in

echo ${arr[@]}
2 2 3

thus only the first (zeroth) element being changed.

I read about awk solutions, but would like to know if BASH arithmetics support such batch operations on each array element.

like image 981
FelixJN Avatar asked Sep 13 '26 02:09

FelixJN


1 Answers

I know your question is not fresh new but you can accomplish what you want by declaring your array as integer and then applying a substitution:

declare -ia arr=( 1 2 3 )
value=1

declare -ia 'arr_added=( "${arr[@]/%/+$value}" )'
echo "arr_added: ${arr_added[*]}"

value=42
declare -ia 'arr_added=( "${arr[@]/%/+$value}" )'
echo "arr_added: ${arr_added[*]}"

It outputs:

arr_added: 2 3 4
arr_added: 43 44 45

You can perform other math operations as well:

value=3
declare -ia 'arr_multd=( "${arr[@]/%/*$value}" )'
echo "arr_multd: ${arr_multd[*]}"

Outputs:

arr_multd: 3 6 9
like image 121
j4x Avatar answered Sep 14 '26 16:09

j4x



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!