The find / sort solution works great until the number of files gets really large (like an entire file system). Use awk instead to just keep track of the most recent file:
find $DIR -type f -printf "%T@ %p\n" |
awk '
BEGIN { recent = 0; file = "" }
{
if ($1 > recent)
{
recent = $1;
file = $0;
}
}
END { print file; }' |
sed 's/^[0-9]*\.[0-9]* //'
All those ls/tail solutions work perfectly fine for files in a directory - ignoring subdirectories.
In order to include all files in your search (recursively), find can be used. gioele suggested sorting the formatted find output. But be careful with whitespaces (his suggestion doesn't work with whitespaces).
This should work with all file names:
find $DIR -type f -printf "%T@ %p\n" | sort -n | sed -r 's/^[0-9.]+\s+//' | tail -n 1 | xargs -I{} ls -l "{}"
This sorts by mtime, see man find:
%Ak File's last access time in the format specified by k, which is either `@' or a directive for the C `strftime' function. The possible values for k are listed below; some of them might not be available on all systems, due to differences in `strftime' between systems.
@ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part.
%Ck File's last status change time in the format specified by k, which is the same as for %A.
%Tk File's last modification time in the format specified by k, which is the same as for %A.
The find / sort solution works great until the number of files gets really large (like an entire file system). Use awk instead to just keep track of the most recent file:
I use:
ls -ABrt1 --group-directories-first | tail -n1
It gives me just the file name, excluding folders.
All those ls/tail solutions work perfectly fine for files in a directory - ignoring subdirectories.
In order to include all files in your search (recursively), find can be used. gioele suggested sorting the formatted find output. But be careful with whitespaces (his suggestion doesn't work with whitespaces).
This should work with all file names:
This sorts by mtime, see man find:
So just replace
%T
with%C
to sort by ctime.I like
echo *(om[1])
(zsh
syntax) as that just gives the file name and doesn't invoke any other command.Presuming you don't care about hidden files that start with a
.
Otherwise
ls -lAtr | tail -1
The other solutions do not include files that start with
'.'
.This command will also include
'.'
and'..'
, which may or may not be what you want:ls -latr | tail -1