Random Wisdom

Create links with absolute paths in Linux

by on Jan.16, 2010, under How To ..., Linux, Software

The default behaviour of the linking command (ln) is a little strange under certain circumstances. Since it creates the links using the literal value of the target, symbolic links created using relative path structures can often fail. Consider the following:

$ ln -s targetfile ../src/targetfile_link

Without a doubt, ‘targetfile_link’ will be a broken symlink since it links to a target that it assumes is in the same directory:

$ cd ../src && ls -l targetfile_link
lrwxrwxrwx 1 mafgani mafgani 5 2010-01-16 18:19 targetfile_link -> targetfile

This is quite unfortunate since it clearly clashes with the way that the linking mechanism should work intuitively.

The solution is to force ln into automatically appending the absolute path to the target files. This can be achieved by using a simple shell script that acts as a wrapper for the real linking command:


# Step through the supplied arguments and append the absolute
# path to targets that exist
for ARG in $@
  if [ -e $ARG ]; then
    LNARGS="${LNARGS} ${PWD}/${ARG}";
    LNARGS="${LNARGS} ${ARG}";

# Execute the actual link command with the modified args
exec /bin/ln ${LNARGS};

There are two known caveats:

  • The link is ‘sub-optimal’ if created from within the destination directory (the absolute path contains ‘../’s). It will still work however.
  • The links will always be absolute. If that is undesirable, save the script as ‘absln’ or something other than ‘ln’.

Using ‘absln’ instead of ‘ln’ in the previously described scenario now produces a working symlink:

$ absln -s targetfile ../src/targetfile_link
$ cd ../src/ && ls -l targetfile_link
lrwxrwxrwx 1 mafgani mafgani 16 2010-01-16 19:13 targetfile_link -> /tmp/files/targetfile
:, , , , ,

1 Comment for this entry

  • mark

    Unfortunately there’s one problem to this.

    touch /tmp/readme.txt
    mkdir /tmp/a
    cd /tmp/a
    ln -s ../readme.txt /home/user/readme.txt
    cd ..
    rmdir /tmp/a
    cat /home/user/readme.txt

    won’t work.

    Also if that directory is not accessible due to permissions instead of being removed, also breaks the link.

Leave a Reply