Search code examples
bashshellcommand-linedirectorytail

Enter last directory in path and tail last file in directory


I have on daily bases need to watch the logs during our testing. This is always a pain in the * as I always have to enter the log directory, copy the name of last directory, than copy the name of last log file in directory and tail it which takes a lot of time, I was wondering if there is any combination of commands which would do this automatically so I could alias it.

So I know to select last file/directory I can use this:

ls | tail -1

And I know to watch log file updating I can use:

tail -f

But is there a combination of commands which would go like this:

  1. Select last directory in logs directory
  2. Select last .log file in that directory
  3. "tail -f" the last file in direcotry

Thank you for all your help.


Solution

  • To sort files by date reliably:

    list_date_sorted_ascending() {
        while IFS= read -r -d '' -u 9
        do
            printf '%q\0' "${REPLY#* }"
        done 9< <(find "$1" -mindepth 1 -maxdepth 1 -printf '%T@' -exec printf ' %s\0' {} \; | sort --general-numeric-sort --zero-terminated)
    }
    

    To be able to use head and tail on NUL-separated output:

    nul_terminated() {
        tr '\0\n' '\n\0' | "$@" | tr '\0\n' '\n\0'
    }
    

    Putting it together:

    tail -f "$(list_date_sorted_ascending /var/log | nul_terminated tail -n 1)"