How to resolve symbolic links in a shell script

Posted by Greg Hewgill on Stack Overflow See other posts from Stack Overflow or by Greg Hewgill
Published on 2008-08-11T10:40:41Z Indexed on 2010/03/18 9:41 UTC
Read the original article Hit count: 817

Filed under:
|
|
|
|

Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.

If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):

$ ls -ld foo bar
drwxr-xr-x   2 greg  greg  68 Aug 11 22:36 bar
lrwxr-xr-x   1 greg  greg   3 Aug 11 22:36 foo -> bar
$ cd foo
$ pwd
/Users/greg/tmp/foo
$

What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar".

© Stack Overflow or respective owner

Related posts about shell

Related posts about scripts