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
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.
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.
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
Remove the 2 extra spaces like this:
config[$i]="value2"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With