3

What is the difference between (*) and ("$(ls)")?

Are they essentially the same except the delimiters are different?

tmpbin
  • 763

1 Answers1

5

The first one, (*), globs the list of files and directories in the current directory and creates a list. You can assign that list to an array variable, and each file name will be its own entry.

touch 'a b' c
d=(*)
printf "> %s <\n" "${d[@]}"
> a b <
> c <

The second one, (“$(ls)”), invokes ls to list the current directory. The resulting list of files and directories is put into a single string and assigned to a list. The list contains this single element consisting of the newline-separated set of names.

d=("$(ls)")
printf "> %s <\n" "${d[@]}"
> a b
c <

The first one is better as the file names are posted properly into individual elements of the list, and parsing the output of ls is often fraught with unexpected complications

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
  • 1
    Very good answer. For those new to shell programming, I would just add that anything, like ("$(ls)"), that involves parsing the output of ls generally considered to be an abomination. – John1024 Jul 04 '20 at 21:39