How to check if a symlink exists

前端 未结 8 2076
無奈伤痛
無奈伤痛 2020-12-04 05:04

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         


        
8条回答
  •  臣服心动
    2020-12-04 05:57

    How about using readlink?

    # if symlink, readlink returns not empty string (the symlink target)
    # if string is not empty, test exits w/ 0 (normal)
    #
    # if non symlink, readlink returns empty string
    # if string is empty, test exits w/ 1 (error)
    simlink? () {
      test "$(readlink "${1}")";
    }
    
    FILE=/usr/mda
    
    if simlink? "${FILE}"; then
      echo $FILE is a symlink
    else
      echo $FILE is not a symlink
    fi
    

提交回复
热议问题