trip0d199
trip0d199

Reputation: 228

apply a numeric offset to each element in a bash array

I would like to take the user's input and decrement each value taken in by one. For example, if the user provides:

0 1 6 8

I would like to change this to:

-1 0 5 7

My code looks like this, but doesn't seem to work:

echo 'Please enter numbers:'
read numbers
IFS=' '
numarray=($numbers)
for i in "${numarry[@]}"
do
     (( numarray[i]-- )) 
done
echo ${numarray[@]}

But the code doesnt seem to work. Any ideas? Thanks for your help.

Upvotes: 0

Views: 225

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200373

Your code doesn't work as you expect, because for i in ${numarray[@]} iterates over the elements of the array with $i being the actual elements, whereas (( numarray[i]-- )) expects $i to be the index of the array elements. Try this:

echo 'Please enter numbers:'
read numbers
IFS=' '
numarray=($numbers)
numarray=($numbers)
for i in $(seq 1 ${#numarry[@]}); do
  (( numarray[i-1]-- )) 
done
echo ${numarray[@]}

Upvotes: 1

Related Questions