1

I have the following simple shell command:

for x in $(echo one two three); do echo $x; done

When executed, it simply prints

one two three

on one line, i. e. the result of the command substitution is evaluated as though I'd quote one two three, like so:

for x in "one two three"; do echo $x; done

However, I'd rather want the returned text of the command substitution to be returned as individual words, much like

for x in one two three; do echo $x; done

so that it prints

one
two
three

Is this somehow possible?

2
  • What you're asking for is the default behavior. Did you change IFS? Commented Sep 13, 2024 at 15:09
  • What shell are you using? Commented Sep 13, 2024 at 16:14

1 Answer 1

1

By default, unquoted command substitution, in Bourne-like shells, when in list context (and that for loop in part is a list context obviously) is subject to split+glob (split only in zsh)

The splitting is done on characters of $IFS which by default includes space, tab and newline (and null in zsh).

So:

for x in $(echo one two three); do echo $x; done

Should loop over one, two, three as long as you've not modified $IFS from its default¹. Note that globbing is also performed in shells other than zsh which you almost never want. It's harmless here, but would become a problem if there was a * word for instance in the output of echo.

And also note that split+glob is also performed on unquoted parameter expansions, so that $x should be "$x".

Unsetting $IFS also reverts the default splitting, so if you want to account for a $IFS that might have been modified earlier, you can do:

unset -v IFS # split on space, tab, newline
set -o noglob # except in zsh
for x in $(echo one two three); do echo "$x"; done

¹ And those are really regular U+0020 space characters, not one of the     other space characters found in Unicode that terminal emulators usually display the same as U+0020; you can add them to $IFS, but in most shells, the splitting will not behave like for space/tab/newline in that leading and trailing ones won't be ignored and each individual occurrence will delimit a field.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.