How to check if a symlink exists

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.


-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.


-L is the test for file exists and is also a symbolic link

If you do not want to test for the file being a symbolic link, but just test to see if it exists regardless of type (file, directory, socket etc) then use -e

So if file is really file and not just a symbolic link you can do all these tests and get an exit status whose value indicates the error condition.

if [ ! ( -e "${file}" ) ]
then
     echo "%ERROR: file ${file} does not exist!" >&2
     exit 1
elif [ ! ( -f "${file}" ) ]
then
     echo "%ERROR: ${file} is not a file!" >&2
     exit 2
elif [ ! ( -r "${file}" ) ]
then
     echo "%ERROR: file ${file} is not readable!" >&2
     exit 3
elif [ ! ( -s "${file}" ) ]
then
     echo "%ERROR: file ${file} is empty!" >&2
     exit 4
fi

You can check the existence of a symlink and that it is not broken with:

[ -L ${my_link} ] && [ -e ${my_link} ]

So, the complete solution is:

if [ -L ${my_link} ] ; then
   if [ -e ${my_link} ] ; then
      echo "Good link"
   else
      echo "Broken link"
   fi
elif [ -e ${my_link} ] ; then
   echo "Not a link"
else
   echo "Missing"
fi
链接地址: http://www.djcxy.com/p/78102.html

上一篇: Windows中的Git符号链接

下一篇: 如何检查符号链接是否存在