12

I would like to modify the value to an element of an array and I don't know the syntax to do it

for i in `seq 0 8`;
do
    if [ ${config[$i]} = "value1" ]
        then config[$i] = "value2"    #<- This line
    fi
done

2 Answers 2

14

Technically, the only thing broken there is the whitespace. Don't put spaces around your operators in shell syntax:

config[$i]="value2"

However, there are lots of other little things you may want to think about. For example, if an element of config can contain whitespace, the test can break. Use quotes or the [[ test keyword to avoid that.

… if [[ ${config[$i]} = "value1" ]]
    then config[$i]="value2" …

seq is a nonstandard external executable. You'd be better off using the builtin iteration syntax. Furthermore, assuming the iteration happens over all the elements in config, you probably just want to do:

for ((i=0; i<${#config[@]}; i++));
do
    if [[ ${config[$i]} = "value1" ]]
        then config[$i]="value2"
    fi
done
Sign up to request clarification or add additional context in comments.

Comments

3

Remove the 2 extra spaces like this:

config[$i]="value2"

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.