Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.


2 Answers 2

up vote 5 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.

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"
readlink is your friend. –  JdeBP Aug 31 '11 at 10:37

This site is currently not accepting new answers.

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