0
 ls
> file1 file2 file3

echo *
> file1 file2 file3

foo=$(ls)
echo $foo
> file1 file2 file3

echo "$foo"
> file1
> file2
> file3

In the last example, why are the filenames displayed on separate lines? Would you explain the steps that the shell (bash) goes through in processing it, please?

Roger Costello
  • 3,007
  • 1
  • 22
  • 43
  • In addition to the linked duplicate -- see [BashParser](https://mywiki.wooledge.org/BashParser) – Charles Duffy Nov 21 '22 at 22:48
  • 3
    One extra thing to understand, though, is that `ls` changes its output format based on whether stdout is going to a TTY. When it's _not_ going direct to a terminal, default behavior acts more like `ls -1`, putting each filename on a different line. – Charles Duffy Nov 21 '22 at 22:49
  • 2
    So `foo=$(ls); echo "$foo"` is presenting the same output that you'd get, say, from `ls | cat`. That's an artifact of `ls`'s design, not of any magic performed by bash; the thing that's an artifact of magic done by bash is `file1 file2 file3` showing up on one line when doing `echo $foo`. – Charles Duffy Nov 21 '22 at 22:51
  • 2
    Also, if you ran `foo=*; echo "$foo"` you would get `*` as output, not a list of filenames at all; so the title is misleading. – Charles Duffy Nov 21 '22 at 23:03
  • also [don't use `ls` output for something else like `$(ls)` or `ls | something`](http://mywiki.wooledge.org/ParsingLs). [Why *not* parse `ls` (and what to do instead)?](https://unix.stackexchange.com/q/128985/44425) – phuclv Nov 22 '22 at 03:35

0 Answers0