6

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?

Mausy5043
  • 906
  • 2
  • 17
  • 39

2 Answers2

15

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.

iBug
  • 35,554
  • 7
  • 89
  • 134
0

I was getting this error when using code below:

redhatCatalogs=("certified-operators" "redhat-marketplace")

for catalog in ${redhatCatalogs[@]}; do
  ...

Notice I am missing the quotes, after adding the quotes, problem was solved:

redhatCatalogs=("certified-operators" "redhat-marketplace")

for catalog in "${redhatCatalogs[@]}"; do
  ...

So in conclusion, consider the quotes as well!: "${redhatCatalogs[@]}"

Cesar Celis
  • 166
  • 1
  • 4
  • 8