Using ls in a command substitution to generate a list of filenames for a list is almost always a poor approach, no matter how you look at it (efficiency, readability, maintainability, robustness (with regard to IFS characters in filenames).
In my opinion (and that's all it is), it's one of the worst yet common scripting practices. I think I see it used just about every day. At least a UUoC is generally harmless. "$(ls *.jpg)" versus a simple "*.jpg" is often buggy.
Regards,
Alister
---------- Post updated at 06:01 PM ---------- Previous update was at 05:49 PM ----------
Quote:
Originally Posted by
KenJackson
But I just now tried that way and Scrutinizer's way and was surprised to find that simple wildcard expansion does work with filenames that have spaces in them, whereas using ls does not.
That's excellent to know, because I sometimes encounter filenames with spaces. So I always try to make all my scripts work seamlessly with them.
The only shell command line parsing step after pattern expansion is quote removal, so it's safe from field splitting and other substitutions/expansions.
Command substitution, however, occurs before field splitting, and is unsafe if the filename contains a character which is used to delimit fields (these characters are denoted by the contents of the IFS variable, whose default value is space, tab, newline). You can quote the command substitution, to prevent field splitting of the command's results, but that would always yield a single word (useless in a loop list context since it would always lead to a single iteration).
Regards,
Alister