Recursively find last modified file in a directory

I need to find the most recent file recursively. Linux find command took around 50 minutes.

Here is a little script to do it faster (less than 2 seconds):

#!/bin/sh
zob () {
    if [ -z ${CURRENT_DIR} ]; then
      CURRENT_DIR="$1"
    fi
    FILE=$(ls -Art1 ${CURRENT_DIR} | tail -n 1)
    if [ ! -f ${FILE} ]; then
        CURRENT_DIR="${CURRENT_DIR}/${FILE}"
        zob
    fi
    echo $FILE
    exit
}
zob $1

It’s a recursive function who get the most recent modified item of a directory. If this item is a directory, the function is called recursively and search into this directory, etc.

To search last modified file in /var/log, just call the script like this:

sh script.sh /var/log

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *