Looking for a command that will return the single most recent file in a directory.
Not seeing a limit parameter to ls
...
ls -Art | tail -n 1
This will return the latest modified file or directory. Not very elegant, but it works.
Used flags:
-A
list all files except .
and ..
-r
reverse order while sorting
-t
sort by time, newest first
ls
to tail
, then prints only the LAST line. IMHO it is better to sort in ascending order and use head
instead, as chaos
suggested. After printing the first line head quits, so sending the next line (actually next block) will rise a SIGPIPE and ls
will quit as well.
ls -t | head -n1
This command actually gives the latest modified file or directory in the current working directory.
ls -tl | head -n 1
, and it doesn't have to push the whole table through the pipe the way mine does.
Nov 14, 2014 at 17:23
ls -Art | head -n1
if you specifically want the latest modified file
head
with tail
. And ideally include --group-directories-first
also.
Feb 24, 2017 at 21:58
This is a recursive version (i.e. it finds the most recently updated file in a certain directory or any of its subdirectory)
find /dir/path -type f -printf "%T@ %p\n" | sort -n | cut -d' ' -f 2- | tail -n 1
Brief layman explanation of command line:
find /dir/path -type f
finds all the files in the directory
-printf "%T@ %p\n"
prints a line for each file where %T@
is the float seconds since 1970 epoch and %p
is the filename path and \n
is the new line characterman find
|
is a shell pipe
(see man bash
section on Pipelines
)sort -n
means to sort on the first column and to treat the token as numerical instead of lexicographic (see man sort
)cut -d' ' -f 2-
means to split each line using the
character and then to print all tokens starting at the second token (see man cut
)
-f 2
would print only the second tokentail -n 1
means to print the last line (see man tail
)find $DIR -type f -exec stat -lt "%Y-%m-%d" {} \+ | cut -d' ' -f6- | sort -n | tail -1
sort -nr
, you can use head -n 1
instead of tail -n 1
and improve efficiency slightly. (Although if you're sorting a recursive find, getting the first or last line won't be the slow part.)
May 14, 2017 at 11:48
find ./ -type f -printf "%T@ %p\n" -ls | sort -n | cut -d' ' -f 2- | tail -n 1 | xargs -r ls -lah
find $DIR -type f -exec stat -lt "%F %T" {} \+ | cut -d' ' -f6- | sort -n | tail -1
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 a bash
array:
eval "files=($(ls -t --quoting-style=shell-always))"
((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"
(add the -A
option to ls
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 (for cut -z
):
readarray -t -d '' files < <(
LC_ALL=C find . -maxdepth 1 -type f ! -name '.*' -printf '%T@/%f\0' |
sort -rzn | cut -zd/ -f2)
((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"
Or recursively:
readarray -t -d '' files < <(
LC_ALL=C find . -name . -o -name '.*' -prune -o -type f -printf '%T@%p\0' |
sort -rzn | cut -zd/ -f2-)
Best here would be to use zsh
and its glob qualifiers instead of bash
to avoid all this hassle:
Newest regular file in the current directory:
printf '%s\n' *(.om[1])
Including hidden ones:
printf '%s\n' *(D.om[1])
Second newest:
printf '%s\n' *(.om[2])
Check file age after symlink resolution:
printf '%s\n' *(-.om[1])
Recursively:
printf '%s\n' **/*(.om[1])
Also, with the completion system (compinit
and co) enabled, Ctrl+Xm becomes a completer that expands to the newest file.
So:
vi Ctrl+Xm
Would make you edit the newest file (you also get a chance to see which it before you press Return).
vi Alt+2Ctrl+Xm
For the second-newest file.
vi *.cCtrl+Xm
for the newest c
file.
vi *(.)Ctrl+Xm
for the newest regular file (not directory, nor fifo/device...), and so on.
zsh
tips. Could you provide a link to more details about this in zsh docs ?
*(.om[1])
, but I usually want to find the newest file in a set of folders, ie. /path/to/folders*/*(.om[1])
, which unfortunately only returns the newest file in all matched folders. See unix.stackexchange.com/questions/552103/… on how to accomplish it over multiple folders.
Sep 7, 2020 at 20:43
c
like find
's -ctime
is for the inode change time which has nothing to do with the creation time. The mtime
can be seen as the creation time of the file's contents (as those are never created in one go). Some systems and filesystems record a birth*/*creation time which is the time a file's inode spawns (possibly again) into existence, but there's no portable API to retrieve that, and zsh has no corresponding sorting qualifier yet. But that particular time is not particularly useful. See When was file created
Nov 7, 2020 at 6:32
-print0
and printf
. Your tip made things quite a bit more elegant than the also-robust BashFAQ/099 (which might get merged with BashFAQ/003).
Sep 16, 2022 at 23:09
I use:
ls -ABrt1 --group-directories-first | tail -n1
It gives me just the file name, excluding folders.
I like echo *(om[1])
(zsh
syntax) as that just gives the file name and doesn't invoke any other command.
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]* //'
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
Shorted variant based on dmckee's answer:
ls -t | head -1
-1
syntax to head has been deprecated quite some time ago, and -n 1
should be used.
If you want to get the most recent changed file also including any subdirectories you can do it with this little oneliner:
find . -type f -exec stat -c '%Y %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done
If you want to do the same not for changed files, but for accessed files you simple have to change the
%Y parameter from the stat command to %X. And your command for most recent accessed files looks like this:
find . -type f -exec stat -c '%X %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done
For both commands you also can change the var="1" parameter if you want to list more than just one file.
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.
I hope this could help.
With only Bash builtins, closely following BashFAQ/003:
shopt -s nullglob
for f in * .*; do
[[ -d $f ]] && continue
[[ $f -nt "$latest" ]] && latest=$f
done
printf '%s\n' "$latest"
Recursively:
find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head
using R recursive option .. you may consider this as enhancement for good answers here
ls -arRtlh | tail -50
ls -t -1 | sed '1q'
Will show the last modified item in the folder. Pair with grep
to find latest entries with keywords
ls -t -1 | grep foo | sed '1q'
1
is for the first line equiv to head -n 1
what is q?
May 9, 2016 at 23:22
try this simple command
ls -ltq <path> | head -n 1
If you want file name - last modified, path = /ab/cd/*.log
If you want directory name - last modified, path = /ab/cd/*/
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.
So just replace %T
with %C
to sort by ctime.
find $DIR -type f -printf "%T@ %p\n" | sort -n | cut -d' ' -f 2- | tail -n 1
Or alternatively, keep all except the first field: find $DIR -type f -printf "%T@ %p\n" | sort -n | cut -d' ' -f 1 --complement | tail -n 1
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" \;
Presuming you don't care about hidden files that start with a .
ls -rt | tail -n 1
Otherwise
ls -Art | tail -n 1
ls -Frt | grep "[^/]$" | tail -n 1
If you want to find the last modified folder name within /apps/test directory then you can put below code snippet in a batch script and execute it which will print the name of the last modified folder name.
#!/bin/bash -e
export latestModifiedFolderName=$(ls -td /apps/test/*/ | head -n1)
echo Latest modified folder within /apps/test directory is $latestModifiedFolderName
I needed to do it too, and I found these commands. these work for me:
If you want last file by its date of creation in folder(access time) :
ls -Aru | tail -n 1
And if you want last file that has changes in its content (modify time) :
ls -Art | tail -n 1
Find the file with prefix of shravan*
and view
less $(ls -Art shravan* | tail -n 1)
watch -n1 'ls -Art | tail -n 1'
- shows the very last filesls
or usefind
without-print0
which is problematic for handling annoying file-names. Always useful to mention: BashFAQ099 which gives a POSIX answer to this problem-printf
with\0
at the end of the output - basically making it a formatted-print0
. For me, it's a lot easier - or at least more elegant - to put the newest (or oldest) filename into a string using what @Stephane_Chazelas shared rather than using BashFAQ/099. Any comments on this are welcome ... in the chat. (P.S. BashFAQ/099 is a great answer and something that I think everyone should know about, by the way.)