5

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.

3
  • What does echo $build_list print? Commented Aug 21, 2019 at 6:47
  • 2
    Better, what does declare -p build_list output Commented Aug 21, 2019 at 6:53
  • It works using build_list=($build_string) Commented Aug 21, 2019 at 8:47

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

4

Replace the second line with this:

build_list=($build_string)

Comments

1

build_list=("$build_string")

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

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.