3

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.

unrue
  • 149
  • 1
  • 2
  • 10

3 Answers3

6

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.

Daemon Painter
  • 3,208
  • 3
  • 29
  • 44
3

Replace the second line with this:

build_list=($build_string)
prefire
  • 66
  • 2
1

build_list=("$build_string")

build_list array only have one item, so ${build_list[@]:1 is empty.

Shaheryar.Akram
  • 722
  • 10
  • 19
黄轩辕
  • 11
  • 2