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, eg 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.
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
you can use eval to have the feeling of lambda function (not sure about the syntax but this should be the main idea ) :
eval "function add1 { x=$1; y=$((x+1)) ; return $y; }"
for (( i=0 ; i<=${#arr[@]}-1 ; i++ )) ; do
add1 ${arr[i]}
done
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.