Looking for a command that will return the single most recent file in a directory.
Not seeing a limit parameter to ls...
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 -t | head -n1
This command actually gives the latest modified file or directory in the current working directory.
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
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.
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"
using R recursive option .. you may consider this as enhancement for good answers here
ls -arRtlh | tail -50
Presuming you don't care about hidden files that start with a .
ls -rt | tail -n 1
Otherwise
ls -Art | tail -n 1