nf.sh 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Define a funtion to list the newest file (nf)
  2. #
  3. # Usage: nf [#] [DIRECTORY]
  4. # Use my utils, constants
  5. source ~/lib/bash/bashutils.sh
  6. nf() (
  7. # Parse args. Alow count or dir a-positinaly.
  8. #
  9. # TODO add more standard arg parsing
  10. # TODO allow flags (e.g. --maxdepth|m=#)
  11. # TODO add --filename|-f flag. No path included.
  12. #
  13. NUM=1
  14. DIR=$(pwd)
  15. if [[ $1 =~ ^[0-9]+$ ]]; then
  16. NUM=$1
  17. DIR=${2:-`pwd`}
  18. elif [[ $2 =~ ^[0-9]+$ ]]; then
  19. NUM=$2
  20. DIR=$1
  21. else
  22. DIR=${1:-`pwd`}
  23. fi
  24. if [ -d "$DIR" ]; then
  25. # Check if the argument is a valid directory
  26. \cd "$DIR" || die "$DIR is not a directory"
  27. # Use find to locate only files, not directories, and list them by modification time
  28. latest_files=$(find . -maxdepth 1 -type f -printf "%T@\t${PWD}/%P\n" | sort -k1 -nr | head -n "${NUM}" | cut -f2-)
  29. if [ -n "$latest_files" ]; then
  30. echo "$latest_files"
  31. else
  32. warn "No files found in the $DIR"
  33. fi
  34. else
  35. info "Usage: $PROGNAME DIRECTORY"
  36. warn "$DIR is not a directory"
  37. return 1
  38. fi
  39. )