Symlink – How to Setup a Symlink to the Most Recent Folder

symlink

I have some directories:

drwxr-xr-x  10 shamoon  staff   320B Mar 20 10:05 dryrun-20200320_140542-1vbczul4
drwxr-xr-x  10 shamoon  staff   320B Mar 20 10:06 dryrun-20200320_140605-uze15jta
drwxr-xr-x  10 shamoon  staff   320B Mar 20 10:06 dryrun-20200320_140644-193bynci
drwxr-xr-x  13 shamoon  staff   416B Mar 20 10:07 dryrun-20200320_140721-fuv399ji
drwxr-xr-x  13 shamoon  staff   416B Mar 20 10:08 dryrun-20200320_140810-34dim70r
drwxr-xr-x  14 shamoon  staff   448B Mar 20 10:10 dryrun-20200320_140935-138yuidx
drwxr-xr-x  14 shamoon  staff   448B Mar 20 10:23 dryrun-20200320_141044-35pfvec6
drwxr-xr-x  14 shamoon  staff   448B Mar 20 11:14 dryrun-20200320_151418-14g88zfr
drwxr-xr-x  14 shamoon  staff   448B Mar 20 12:11 dryrun-20200320_151800-gf551inz
drwxr-xr-x  14 shamoon  staff   448B Mar 20 12:21 dryrun-20200320_161134-wyu9kaxu

I want to set up a symlink to the most recent. Now, there may be more recent directories created, so ideally, the symlink should also automatically update. Is this possible?

Best Answer

This isn't possible to do automatically -- Unix provides no facility for symlinks to dynamically change. However, you can have a program in the background that updates the symlink using inotify and the fact that later files sort as being later with LC_COLLATE=C:

#!/bin/bash -e

export LC_COLLATE=C
shopt -s nullglob

base=/path

while inotifywait -e create \
                  -e moved_to \
                  -e moved_from \
                  -e close_write "$base" > /dev/null; do
    dirs=("$base"/dryrun-[0-9]*/)
    (( ${#dirs[@]} )) && ln -sfn -- "${dirs[-1]}" "$base"/latest
done

And here is the result of it running:

% mkdir dryrun-20200320_140935-138yuidx
% ls -l latest
lrwxrwxrwx 1 cdown cdown 39 Mar 20 16:40 latest -> /path/dryrun-20200320_140935-138yuidx/
% mkdir dryrun-20200320_141044-35pfvec6
% ls -l latest                         
lrwxrwxrwx 1 cdown cdown 39 Mar 20 16:40 latest -> /path/dryrun-20200320_141044-35pfvec6/
Related Question