Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a list in bash

I have this script:

#!/bin/bash

list="a b c d"

for item in ${list[@]}; do
  echo "${item}"
done

When I run it this is the output:

a
b
c
d

This is exactly what I want. However, shellcheck hates this and throws an error:

for item in ${list[@]}; do
            ^-- SC2068: Double quote array expansions to avoid re-splitting elements.

But, when I double quote the variable the output of the script changes to this:

a b c d

Which is not what I want.

Is shellcheck right and should I modify the way I try to extract the items from the variable, but how? Or should I just tell shellcheck to ignore this?

like image 525
Mausy5043 Avatar asked Jan 01 '23 11:01

Mausy5043


1 Answers

This is not an array:

list="a b c d"

You're just assigning list to a string of length 7.

To make it a real array:

list=(a b c d)

Then with for item in "${list[@]}", you get the correct result.


For your updated question, you should just use $list instead of ${list[@]}, because list isn't an array.

like image 175
iBug Avatar answered Jan 23 '23 06:01

iBug