Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Shell function: newest

One of my small shell functions in my user profile is newest which I use on a daily basis. I wrote it about 5 years ago as an easy way to get the filename of the most recently modified file in a given path.

Here's the source of the function:

newest() { 
   [[ ! "$1" = "" ]] && searchdir="$1" || searchdir=".";
   [[ ! "$2" = "" ]] && searchstring="$2" || searchstring="*";
   find $searchdir -name "*$searchstring*" 2> /dev/null | xargs ls -t 2> /dev/null | head -n 1
}

I can tell that my style has changed in the years since I wrote this. Here's how I would write it today. Optionally I would add -maxdepth 1 -mindepth 1 to the find invocation. Maybe that should be another parameter.

newest() {
   ___sdir="." ; test -n "${1}" && ___sdir="${1}" ;
   ___sstr="*" ; test -n "${2}" && ___sstr="${2}" ;
   { find "${___sdir}" -name "*${___sstr}*" | xargs ls -1t | head -n1 ; } 2>/dev/null
}

So what this function does is show the full pathname of the file that is most recently modified. It's great for when you want to edit the most recent file, such as today's log file:

vi $( newest /mnt/public/Support/Systems/server1/var/log/debmirror/ )

Comments