gies0r
gies0r

Reputation: 5239

Get an auto updated symbolic link to the latest file, based on grep on file name

So adapting this SO answer a bit is very close to the solution:

ln -s target-directory/`ls -rt target-directory | grep .log | tail -n1` latest

but how can I actually continously update the sym-link when a new file appears in the directory?

Can this be archived by using inotifywait? How could I install such a job on my system which takes care in the background?

Upvotes: 0

Views: 1531

Answers (1)

P.P
P.P

Reputation: 121407

Note that parsing ls output can be error prone. See bash FAQ 99.

If inotifywait tool is available, you can do something like to get update the symlink.

#!/bin/bash

function newest_log
{
    files=(*.log)
    newest=${files[0]}
    for f in "${files[@]}"; do
        if [[ $f -nt $newest ]]; then
            newest=$f
      fi
    done

    echo $newest
}

while inotifywait -e modify target-directory; do
    ln -s target-directory/$(newest_log) latest
done

You can either run this script directly or setup a service like systemd service.

Upvotes: 1

Related Questions