help-bash
[Top][All Lists]
Advanced

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

Re: ls head and gv


From: Greg Wooledge
Subject: Re: ls head and gv
Date: Sat, 29 Jul 2023 08:11:19 -0400

On Fri, Jul 28, 2023 at 11:11:44PM -0400, David Niklas wrote:
> I used this command:
> alias lgv="gv "$(ls -c *.pdf | head -n1)" &"

Others have mentioned the quoting.  I'll further point out that if
you'd made this a function instead of an alias, the quoting would not
have been an issue.

> What I expected was the latest pdf document to be brought up in gv

Beyond that, the -c option sorts by ctime, which is the last time the
file's metadata (owner, group, permissions, and so on) changed.  If
you want the last modified, you should be sorting by modification
time (mtime), which is what the -t option does.

It's also worth pointing out that using ls to generate filenames has
perils.  Please see <https://mywiki.wooledge.org/ParsingLs> for a
full discussion.

Let's assume you are using GNU coreutils 9.0 or later.  Then you can
do it like this:

lgv() {
    local f
    IFS= read -r -d '' f < <(ls --zero -t *.pdf)
    [[ $f ]] && gv -- "$f" &
}

This calls ls --zero -t to generate a NUL-delimited stream of filenames
sorted by modification time, newest first, and reads the first one into
a local variable.  If there aren't any, then the local variable will
be empty, so it checks that.  If the variable isn't empty, then it runs
gv in the background, passing the filename as an argument, with the
protective -- before it in case the filename begins with a hyphen.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]