Get most recent file in a directory on Linux

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 character
    • for more info see man 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)
    • NOTE: -f 2 would print only the second token
  • tail -n 1 means to print the last line (see man tail)

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.