14

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?

Shamoon
  • 455
  • 1
    under what operating system? When exactly should the symlink be updated -- on a schedule or when a (any?) directory is created? Please edit your question to fill in those details. Thank you! – Jeff Schaller Mar 20 '20 at 16:31
  • If you know how frequently the symlink should be updated you can create a cron job doing a simple ln -s $(ls - t | head -n 1) link_name. –  Mar 20 '20 at 16:43
  • 2
    If you control the (running of) the software that creates these directories, you can run the ln -sf $DIR latest when this software runs (e.g. if it is a python script or something like that). Note that you need the -f for when the symlink already exists. – user7761803 Mar 21 '20 at 07:32

2 Answers2

21

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/
Chris Down
  • 125,559
  • 25
  • 270
  • 266
7

No. not a symlink, but it is possible by mounting a fuse file-system. I don't know of any fuse file-system that does this. But it is possible to create one.