Update symlinks to always point to the newest file in folder

Say you have a directory as the following:

% tree .
.
├── foo.1
├── foo.10
├── foo.11
├── foo.2
├── foo.3
├── foo.4
├── foo.5
├── foo.6
├── foo.7
├── foo.8
├── foo.9
├── moo.1
├── moo.10
├── moo.11
├── moo.2
├── moo.3
├── moo.4
├── moo.5
├── moo.6
├── moo.7
├── moo.8
└── moo.9

… and you want to create 2 symlinks somewhere else so that they point to the files with the highest number for each file name. There will be two links foo, which points to foo.11, and moo, which points to moo.11. These symlinks should be updated by a cronjob.

Here is a small and probably dirty shell script, when run as a cronjob is doing exactly this.

#!/bin/sh

FILE_BASE=foo
SOURCE_FOLDER=/home/wose/tmp/source
TARGET_LINK=/home/wose/tmp/target/foo

HIGHEST_NUMBER=$(find "$SOURCE_FOLDER" -name "*$FILE_BASE*" | sed -r 's/.*\.([0-9]+$)/\1/' | sort -n | tail -n 1)

TARGET_FILE=$(find "$SOURCE_FOLDER" -name "$FILE_BASE.$HIGHEST_NUMBER")

if [ -f $TARGET_LINK ];
then
    rm $TARGET_LINK
fi

ln -s $TARGET_FILE $TARGET_LINK

For each symlink you want to update you would need one copy of this script.

March 24, 2013 | linux, shell, cron
about | blog | archives