首页 文章

如何检查符号链接是否存在

提问于
浏览
166

我正在尝试检查bash中是否存在符号链接 . 这是我尝试过的 .

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

但是,这不起作用 . 如果'!'被遗漏,它永远不会触发 . 而如果 '!'在那里,它每次都会触发 .

8 回答

  • 1

    如果"file"存在且 -L 是符号链接(链接文件可能存在,也可能不存在),则返回 -L . 你想要 -f (如果文件存在并且是常规文件则返回true)或者只是 -e (如果文件存在则返回true,无论类型如何) .

    根据GNU manpage-h-L 相同,但根据BSD manpage,不应使用它:

    -h file如果文件存在且为符号链接,则为真 . 保留此运算符以与此程序的先前版本兼容 . 不要依赖它的存在;请改用-L .

  • 23

    -L是文件存在的测试,是 also 的符号链接

    如果你不想测试文件是一个符号链接,只是测试它是否存在,无论类型(文件,目录,套接字等),然后使用-e

    因此,如果文件确实是文件而不仅仅是符号链接,则可以执行所有这些测试并获得退出状态,其值指示错误情况 .

    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
    
  • 4

    您可以检查符号链接是否存在,并且它没有被破坏:

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

    因此,完整的解决方案是:

    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
    
  • 259

    也许这就是你要找的东西 . 检查文件是否存在且不是链接 .

    试试这个命令:

    file="/usr/mda" 
    [ -f $file ] && [ ! -L $file ] && echo "$file exists and is not a symlink"
    
  • 14

    使用 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
    
  • 2

    该文件真的是一个象征性的链接吗?如果没有,通常的存在测试是 -r-e .

    man test .

  • 36

    如果您正在测试文件是否存在,则需要-e not -L . -L测试符号链接 .

  • 5
    • 首先你可以用这种风格:
    mda="/usr/mda"
    if [ ! -L "${mda}" ]; then
      echo "=> File doesn't exist"
    fi
    
    • 如果你想用更高级的风格来做,你可以像下面这样写:
    #!/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
    

    以上结果如下:

    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
    

相关问题