I personally prefer to use as few not built-in bash commands as I can (to reduce the number of expensive fork and exec syscalls). To sort by date the ls needed to be called. But using of head is not really necessary. I use the following one-liner (works only on systems supporting name pipes):
read newest < <(ls -t *.log)
or to get the name of the oldest file
read oldest < <(ls -rt *.log)
(Mind the space between the two '<' marks!)
If the hidden files are also needed -A arg could be added.
Finding the most current file in every directory according to a pattern, e.g. the sub directories of the working directory that have name ending with "tmp" (case insensitive):
find . -iname \*tmp -type d -exec sh -c "ls -lArt {} | tail -n 1" \;
Shorted variant based on dmckee's answer:
Not very elegant, but it works.
I personally prefer to use as few not built-in
bash
commands as I can (to reduce the number of expensive fork and exec syscalls). To sort by date thels
needed to be called. But using ofhead
is not really necessary. I use the following one-liner (works only on systems supporting name pipes):or to get the name of the oldest file
(Mind the space between the two '<' marks!)
If the hidden files are also needed -A arg could be added.
I hope this could help.
A note about reliability:
Since the newline character is as valid as any in a file name, any solution that relies on lines like the
head
/tail
based ones are flawed.With GNU
ls
, another option is to use the--quoting-style=shell-always
option and abash
array:(add
-A
if you also want to consider hidden files).If you want to limit to regular files (disregard directories, fifos, devices, symlinks, sockets...), you'd need to resort to GNU
find
.With bash 4.4 or newer (for
readarray -d
) and GNU coreutils 8.25 or newer (forcut -z
):Or recursively:
Best here would be to use
zsh
and its glob qualifiers instead ofbash
to avoid all this hassle:Newest regular file in the current directory:
Including hidden ones:
Second newest:
Check file age after symlink resolution:
Recursively:
Also, with the completion system (
compinit
and co) enabled, Ctrl+Xm becomes a completer that expands to the newest file.So:
Would make you edit the newest file (you also get a chance to see which it before you press Return).
For the second-newest file.
for the newest
c
file.for the newest regular file (not directory, nor fifo/device...), and so on.
Finding the most current file in every directory according to a pattern, e.g. the sub directories of the working directory that have name ending with "tmp" (case insensitive):
Recursively: