Reputation: 197
In bash, I have a string, I want to convert in array and use it in a for loop but skipping the first element. The code below does not works:
build_string="100 99 98"
build_list=("$build_string")
echo $build_list
for i in "${build_list[@]:1}"
do echo "i: " $i
done
The for loop does not print anything. Could you help me? Thanks.
Upvotes: 5
Views: 13899
Reputation: 11
build_list=("$build_string")
build_list
array only have one item, so
${build_list[@]:1
is empty.
Upvotes: 1
Reputation: 3470
I believe you are not converting the array properly (or at all). Please see this snippet:
build_string="100 99 98"
#build_list=("$build_string") <-- this is not converting into array, following line is.
IFS=' ' read -r -a build_list <<< "$build_string"
echo $build_list
for i in "${build_list[@]:1}"
do echo "i: " $i
done
sleep 2
now the output is:
100
i: 99
i: 98
Which sounds reasonable. The 100
is printed when you ask echo $build_string
.
Reference: split string into array in bash
As pointed out by prefire, the double quotes on the second line are preventing array conversion. This snippet also works:
build_string="100 99 98"
build_list=($build_string)
echo $build_list
for i in "${build_list[@]:1}"
do echo "i: " $i
done
sleep 2
Note: I've added a sleep 2
at the end, so I can see what is being printed.
Upvotes: 7