Stephen K. Karanja
Stephen K. Karanja

Reputation: 498

Shell script file existence test fails for broken symbolic link

This Bourne shell script fails to detect the existence of a broken symbolic link. It returns false and doesn't echo yet /usr/bin/firefox.real is a file that exists but as a broken symbolic link. Why?

FIREFOX="/usr/bin/firefox.real"

[ -e "$FIREFOX" ] && echo "exists"

Upvotes: 3

Views: 623

Answers (2)

user4129403
user4129403

Reputation:

The reason is that internally, bash will call fstat(), not lstat() when you test with -e, so it checks the file itself, not the symbolic link.

Upvotes: 1

anubhava
anubhava

Reputation: 785146

Use -h to check for existence of a link (even broken):

[ -h "$FIREFOX" ] && echo "exists"

As per man test:

  -h FILE
          FILE exists and is a symbolic link (same as -L)

Upvotes: 2

Related Questions