How to check if a symlink exists

前端 未结 8 2045
無奈伤痛
無奈伤痛 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 06:02

    Is the file really a symbolic link? If not, the usual test for existence is -r or -e.

    See man test.

    0 讨论(0)
  • 2020-12-04 06:03
    1. first you can do with this style:

      mda="/usr/mda"
      if [ ! -L "${mda}" ]; then
        echo "=> File doesn't exist"
      fi
      
    2. if you want to do it in more advanced style you can write it like below:

      #!/bin/bash
      mda="$1"
      if [ -e "$1" ]; then
          if [ ! -L "$1" ]
          then
              echo "you entry is not symlink"
          else
              echo "your entry is symlink"
          fi
      else
        echo "=> File doesn't exist"
      fi
      

    the result of above is like:

    root@linux:~# ./sym.sh /etc/passwd
    you entry is not symlink
    root@linux:~# ./sym.sh /usr/mda 
    your entry is symlink
    root@linux:~# ./sym.sh 
    => File doesn't exist
    
    0 讨论(0)
提交回复
热议问题