24

Within a bash script, I know I can check if a file is a symbolic link with the following syntax

if [ -L $path ]

Does any one know how I would test if that path was linked to a particular path? E.g. I want to check whether the target of $path is /some/where.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
BillMan
  • 343
  • 1
  • 2
  • 6
  • possible duplicate of [How do I check if a file is a symbolic link to a directory?](http://unix.stackexchange.com/questions/96907/how-do-i-check-if-a-file-is-a-symbolic-link-to-a-directory) – A.B. Mar 24 '15 at 20:54
  • 2
    Do you mean linked to _by_ a particular path? Couldn't you do a `readlink` on the known path and compare it against the path you're testing? – Bratchley Mar 24 '15 at 20:55
  • @Bratchley. Yes, that's what I meant.. thanks for the answer. – BillMan Mar 24 '15 at 20:57
  • 3
    I strongly urge you to always put shell variables in quotes (e.g., `if [ -L "$path" ]` ) unless you have a good reason not to and you're sure you know what you're doing. – G-Man Says 'Reinstate Monica' Mar 25 '15 at 00:02
  • @G-Man thanks for the great feedback.. subconsciously I know to do that, but forget it in practice.. the reinforcement helps. – BillMan Mar 25 '15 at 13:23

1 Answers1

31

If you want to check whether $path is a symbolic link whose target is /some/where, you can use the readlink utility. It isn't POSIX, but it's available on many systems (GNU/Linux, BusyBox, *BSD, …).

if [ "$(readlink -- "$path")" = /some/where ]; then …

Note that this is an exact text comparison. If the target of the link is /some//where, or if it's where and the value of $path is /some/link, then the texts won't match.

Many versions of readlink support the option -f, which canonicalizes the path by expanding all symbolic links.

Many shells, including dash, ksh, bash and zsh, support the -ef operator in the test builtin to test whether two files are the same (hard links to the same file, after following symbolic links). This feature is also widely supported but not POSIX.

if [ "$path" -ef "/some/where" ]; then …
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175