How to check if a symlink exists

bear picture bear · Apr 23, 2011 · Viewed 295.4k times · Source

I'm trying to check if a symlink exists in bash. Here's what I've tried.

mda=/usr/mda
if [ ! -L $mda ]; then
  echo "=> File doesn't exist"
fi


mda='/usr/mda'
if [ ! -L $mda ]; then
  echo "=> File doesn't exist"
fi

However, that doesn't work. If '!' is left out, it never triggers. And if '!' is there, it triggers every time.

Answer

drysdam picture drysdam · Apr 23, 2011

-L returns true if the "file" exists and is a symbolic link (the linked file may or may not exist). You want -f (returns true if file exists and is a regular file) or maybe just -e (returns true if file exists regardless of type).

According to the GNU manpage, -h is identical to -L, but according to the BSD manpage, it should not be used:

-h file True if file exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead.