Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

If I have a symbolic link /var/opt/foo created with ln -fs /path/to/target/dir foo. How can I in a script that sees only the link get /path/to/target/dir?

What I want to achieve in the script is rm -rf /path/to/target/dir before I do ln -fs /path/to/another/dir foo.

share|improve this question
up vote 15 down vote accepted

target=$(readlink "$link")

$target is now the target of the link, exactly as it was stored in the filesystem.

Symlinks can be relative, though, so this would be better for normal usage:

target=$(readlink -f "$link")

Note that this uses readlink from GNU Coreutils, which may not exist in BSD and other systems.

Edit: readlink -f works on BSDs, as long as the link target exists. realpath is another, BSD-only, tool that works in a similar way.

share|improve this answer
Thanks, I knew there was a better way but my google-fu was weak today. – Nifle Aug 31 '11 at 11:51
The BSDs have had a readlink() system call since the days of 4.2BSD. The current BSDs' readlink utility was released with FreeBSD 4.10. It was (re)implemented as a hard link for the stat command (MacOS X manual page FreeBSD 9 manual page). Notice that it doesn't have a -m option. – JdeBP Aug 31 '11 at 14:55
@JdeBP: Thanks. It does have -f, and readlink -f works just as well (assuming the link target exists). In BSD, realpath appears to be another alternative to readlink -m. – grawity Aug 31 '11 at 15:00

One way is (I'm hoping for a better version)

cd /var/opt/foo
cd $olddir
rm -rf "$olddir"
share|improve this answer
readlink is your friend. – JdeBP Aug 31 '11 at 10:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .