1

I have an array with different values, and if the value is 3 (integer) this value will be exchanged for 999 (integer). But I have a syntax problem in the 'if' block of the array.

The correct return would be: 1 999 5 7 9 999

vetor=(1 3 5 7 9 3)
for i in ${vetor[*]}
do
    if [[ ${vetor[i]} = 3 ]]; then
        ${vetor[i]} = 999
    fi
    echo $i
done
1
  • 1
    vetor[i]=999 there are no spaces surrounding '=' when used for assignment. You do not use $ (dereference) when making assignment. Also understand [[ ${vetor[i]} = 3 ]] makes a string comparison, while [[ ${vetor[i]} -eq 3 ]] makes a numeric comparison. Changing vetor[i] does not change the loop variable i. Commented May 22, 2021 at 3:09

1 Answer 1

1

This produces the correct output in Bash:

vetor=(1 3 5 7 9 3);
for i in ${!vetor[*]};
do
     if [[ ${vetor[i]} -eq 3 ]]; then
         vetor[i]=999;
     fi;
     echo ${vetor[i]};
done

I added ! in the for loop expression to get the indices of vetor instead of the values, and I removed the ${} around the assignment in the if condition (this was giving "if 3 is not a typo" warnings). Also changed the echo to get the value at vetor[i] instead of printing the index.

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.