On Tue, Oct 08, 2019 at 12:47:15AM +1100, Andrew McGlashan wrote:
> I've been "reprimanded" in the past for doing something like
>
>    for filex in $(ls 6H9*)
>    ...
>
>
> Everyone says, don't use "ls", it isn't needed.

It's true that ls isn't needed, but the real problem is that parsing the
output of ls is unreliable and potentially dangerous. And it can't deal with
filenames which have completely valid characters like spaces, tabs, newlines,
and shell meta-characters.

The **ONLY** characters that are not valid in a unix filename are
forward-slash and NUL.  **ALL** other characters are valid.  If you write your
scripts without taking that into account then your scripts are broken.

The output of ls should never be used for anything other than viewing in a
terminal.


See 
https://unix.stackexchange.com/questions/128985/why-not-parse-ls-and-what-to-do-instead

In short, use shell globbing (aka "wildcard" characters).  If globs can't do
what you want, use find rather than ls.

Either with 'find ... -exec' or, if you need to process find's list of
filenames (with grep or sed or something) make sure you use NUL separated
output and tools that can handle NUL-separated input (e.g. 'find ... -print0 |
grep -z ... | head -z -n 10 | xargs -0r')

Most GNU tools these days have a '-z' option for that. some others do too.
and perl has '-0', as does 'xargs'.  With awk you can set the input (and/or
output) record separator with RS="\0" (or ORS="\0").

craig

--
craig sanders <[email protected]>
_______________________________________________
luv-main mailing list
[email protected]
https://lists.luv.asn.au/cgi-bin/mailman/listinfo/luv-main

Reply via email to