0

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.

1 Answer 1

1

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[@]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.