[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: The ls command



On Fri, Oct 31, 2025 at 18:31:08 -0500, David Wright wrote:
> I'd agree with that, with the odd exception where the range of
> filenames is strictly limited. For example, ls -t1 is hard to
> beat for simplicity, compared with using find+printf+sort+cut
> or find+stat+sort+cut.

Saying "Hey, my files are always alphanumeric plus dots; no other
characters will ever be used!" is not acceptable to me.  This will not
remain true.  Either someone will start using unrestricted filenames,
or the tool will start to be used in other contexts, and either way,
you lose.

So, this is where it gets complicated.  POSIX ls is not usable for
this task.  If the script needs to be portable beyond GNU/Linux systems,
you'll need to find another way.

If the script only needs to work on bash + recent GNU coreutils, then
there are a couple viable approaches.

The first way is the --zero option.  This is my preference.

    readarray -d '' files < <(ls -t --zero)

The second way uses --quoting-style.  This is uglier, but works with
slightly older coreutils.

    eval "files=( $(ls -t --quoting-style=shell-always) )"

Both of these approaches are documented more verbosely on
<https://mywiki.wooledge.org/ParsingLs#Notes_on_GNU_coreutils_ls>.

If you aren't using GNU coreutils ls from 2016 or later, then see
the *first* half of the page, before that anchor.


Reply to: