0

A for loop that steps through a list of quoted headers:

for h in "header" "header 2"; do
    echo $h
done

returns

header
header 2

I'd like to reference the headers somewhere else to clean it up, like assigning them to a variable.

headers='"header" "header 2"'
for h in $headers; do
    echo $h
done

but this returns

"header"
"header
2"

as it should.

Is there a way to get around this? It's similar to this post with a list of files with spaces, but I'm not doing files, and I'd like to keep them on one line, as there will be many entries.

  • Can you instead use an array instead of string that has to be word split? – thrig Dec 1 '16 at 21:03
  • What thrig suggested. In other words, if you use Bash, use headers=("header 1" "header 2") and for h in "${headers[@]}"; do echo "$h" ; done. – Nominal Animal Dec 1 '16 at 21:37
2

Another way of doing this is by changing the fiels seperator variable like:

headers="header,header 2"
IFS=,
for h in $headers; do
        echo $h
done

Note: If you have other loops which requires the default IFS value you can first save the IFS value into a temporary variable.

See also man bash and search for IFS for more information.

0

I realized a way around this is to use commas (or something else) instead of quotes, and go csv style. Now it's a simple convert to line-delimited.

headers="header,header 2"
headers=$(echo $headers | sed 's/,/\n/g')
printf "$headers\n" | while read h; do
    echo $h
done

Still, if you have any more elegant solutions, please share.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.