find-newest-file.sh 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env bash
  2. set -euo pipefail # bash strict mode
  3. # newest file
  4. unset -v latest
  5. for file in "$dir"/*; do
  6. [[ $file -nt $latest ]] && latest=$file
  7. done
  8. echo "$latest"
  9. # oldest files
  10. unset -v oldest
  11. for file in "$dir"/*; do
  12. [[ -z $oldest || $file -ot $oldest ]] && oldest=$file
  13. done
  14. # GNU find + GNU sort (To the precision possible on the given OS, but returns only one result)
  15. IFS= read -r -d '' latest \
  16. < <(find "$dir" -type f -printf '%T@ %p\0' | sort -znr)
  17. latest=${latest#* } # remove timestamp + space
  18. # The tempting solution is to use ls to output sorted filenames and operate on the results using e.g. awk. As usual, the ls approach cannot be made robust and should never be used in scripts due in part to the possibility of arbitrary characters (including newlines) present in filenames. Therefore, we need some other way to compare file metadata.
  19. # The most common requirements are to get the most or least recently modified, or largest or smallest files in a directory. Bash and all ksh variants can compare modification times (mtime) using the -nt and -ot operators of the conditional expression compound command:
  20. # Toggle line numbers
  21. # unset -v latest
  22. # for file in "$dir"/*; do
  23. # [[ $file -nt $latest ]] && latest=$file
  24. # done
  25. # Or to find the oldest:
  26. # Toggle line numbers
  27. # unset -v oldest
  28. # for file in "$dir"/*; do
  29. # [[ -z $oldest || $file -ot $oldest ]] && oldest=$file
  30. # done
  31. # Keep in mind that mtime on directories is that of the most recently added, removed, or renamed file in that directory. Also note that -nt and -ot are not specified by POSIX test, but many shells such as dash include them anyway. No bourne-like shell has analogous operators for comparing by atime or ctime, so one would need external utilities for that; however, it's nearly impossible to either produce output which can be safely parsed, or handle said output in a shell without using nonstandard features on both ends.
  32. # If the sorting criteria are different from "oldest or newest file by mtime", then GNU find and GNU sort may be used together to produce a sorted list of filenames + timestamps, delimited by NUL characters. This will operate recursively by default. GNU find's -maxdepth operator can limit the search depth to 1 directory if needed. Here are a few possibilities, which can be modified as necessary to use atime or ctime, or to sort in reverse order:
  33. # Toggle line numbers
  34. # # GNU find + GNU sort (To the precision possible on the given OS, but returns only one result)
  35. # IFS= read -r -d '' latest \
  36. # < <(find "$dir" -type f -printf '%T@ %p\0' | sort -znr)
  37. # latest=${latest#* } # remove timestamp + space
  38. # Toggle line numbers
  39. # 1 # GNU find (To the nearest 1s, using "find -printf" format (%Ts).)
  40. # 2 while IFS= read -rd '' time; do
  41. # 3 IFS= read -rd '' 'latest[time]'
  42. # 4 done < <(find "$dir" -type f -printf '%Ts\0%p\0')
  43. # 5 latest=${latest[-1]}
  44. # One disadvantage to these approaches is that the entire list is sorted, whereas simply iterating through the list to find the minimum or maximum timestamp (assuming we want just one file) would be faster. However, depending on the size of the job, the algorithmic disadvantage of sorting may be negligible in comparison to the overhead of using a shell.
  45. # Toggle line numbers
  46. # 1 # GNU find
  47. # 2 unset -v latest time
  48. # 3 while IFS= read -r -d '' line; do
  49. # 4 t=${line%% *} t=${t%.*} # truncate fractional seconds
  50. # 5 ((t > time)) && { latest=${line#* } time=$t; }
  51. # 6 done < <(find "$dir" -type f -printf '%T@ %p\0')
  52. # Similar usage patterns work well on many kinds of filesystem meta-data. This example gets the largest file in each subdirectory recursively. This is a common pattern for performing a calculation on a collection of files in each directory.
  53. # Readers who are asking this question in order to rotate their log files may wish to look into logrotate(1) instead, if their operating system provides it.