resolve symlinks in Go

See filepath.EvalSymlinks().

EvalSymlinks returns the path name after the evaluation of any symbolic links. If path is relative the result will be relative to the current directory, unless one of the components is an absolute symbolic link.

Examples

Tree:

/bin/sh -> bash
/usr/lib/libresolv.so -> ../../lib/libresolv.so.2

os.Readlink()

os.Readlink("/bin/sh") // => bash
os.Readlink("/usr/lib/libresolv.so") //=> ../../lib/libresolv.so.2

filepath.EvalSymlinks()

filepath.EvalSymlinks("/bin/sh") // => /bin/bash
filepath.EvalSymlinks("/usr/lib/libresolv.so") //=> /lib/libresolv-2.20.so

Note: not absolute path (cd /bin)

 filepath.EvalSymlinks("sh") // => bash
 filepath.EvalSymlinks("/bin/sh") // => /bin/bash

And somthing more

 filepath.EvalSymlinks("/bin/bash") // => /bin/bash
 // but
 os.Readlink("/bin/bash") // => error: readlink /bin/bash: invalid argument

Example application not for playground


Use os.Lstat:

func Lstat(name string) (fi FileInfo, err error)

Lstat returns a FileInfo describing the named file. If the file is a symbolic link, the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link. If there is an error, it will be of type *PathError.

EDIT:

Then returned os.FileInfo will only allow you to check if 'name' is a link or not (fi.Mode() & os.ModeSymlink != 0). If it is, then use os.Readlink to get the pointee:

func Readlink(name string) (string, error)

Readlink returns the destination of the named symbolic link. If there is an error, it will be of type *PathError.

Tags:

Symlink

Go