How to check if a symlink exists

前端 未结 8 2081
無奈伤痛
無奈伤痛 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:45

    -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
    

提交回复
热议问题