3

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

Are they essentially the same except the delimiters are different?

3

1 Answer 1

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

1
  • 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 4, 2020 at 21:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .