Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value to element of an array inside a loop in bash

Tags:

bash

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
like image 920
Sadiel Avatar asked Sep 17 '12 19:09

Sadiel


People also ask

How do you assign a value to an array element?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

How do I loop through an array in bash?

There are two ways to iterate over items of array using For loop. The first way is to use the syntax of For loop where the For loop iterates for each element in the array. The second way is to use the For loop that iterates from index=0 to index=array length and access the array element using index in each iteration.


2 Answers

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
like image 139
kojiro Avatar answered Sep 28 '22 07:09

kojiro


Remove the 2 extra spaces like this:

config[$i]="value2"
like image 41
Stephane Rouberol Avatar answered Sep 28 '22 07:09

Stephane Rouberol