How get full path to target of link
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
.
Solution 1:
link=/var/opt/foo
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.