2011-04-23 84 views
137

我试图检查符号链接是否存在于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 

但是,这是行不通的。 如果'!'被排除在外,它从不触发。而如果 '!'在那里,它每次都会触发。

+1

为什么它的价值,如果你使用[[! - D $ mda]]工作得很好.. – DMin 2017-12-13 06:55:01

回答

219

-L如果“文件”存在并且是符号链接(链接的文件可能存在也可能不存在),则返回true。您需要-f(如果文件存在并且是常规文件,则返回true)或者可能只是-e(如果文件不管类型是否存在,则返回true)。

按照GNU manpage-h相同-L,但根据BSD manpage,它不应该被用于:

-h file真,如果文件存在且是一个符号链接。该操作员被保留以与该程序的先前版本兼容。不要依赖它的存在;用-L代替。

+2

我正在查看符号链接是否不存在。 !-h或!-L应该适用于符号链接,!-e应该以其他方式工作。 – bear 2011-04-23 21:32:27

+30

为了帮助那些像我一样通过Google找到它的人,使用'!'的完整语法是'if! [-L $ mda];然后...... fi'即将感叹号放在方括号外。 – Sam 2012-09-05 08:06:48

+13

只是想给@Sam给出的提示添加一些内容;当做这些操作时,请确保将文件名放在引号中,以防止空白问题。 例如'如果[! -L“$ mda”];然后... fi'(注意:'如果[!...]'和'if![...]'相同:) – 2013-08-06 12:26:10

1

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

+0

我正在查看符号链接是否不存在。 !-h或!-L应该适用于符号链接,!-e应该以其他方式工作。 – bear 2011-04-23 21:32:08

+3

你想要什么不清楚。该文件存在并不是符号链接?然后测试* -e和!-h。 – 2011-04-23 21:40:09

+0

文件位是一个错误,它是一个符号链接,而不是文件本身。 – bear 2011-04-23 21:41:41

3

该文件是否真的是符号链接?如果不是,通常存在的测试是-r-e

参见man test

13

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

试试这个命令:

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

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

如果你不想来测试该文件是一个符号链接,但只是测试,看看它是否存在无论类型(文件,目录,套接字等),然后使用-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 
+9

如果符号链接存在但其目标不存在,'-e“$ {file}”'失败。 – Flimm 2012-05-31 11:17:52

+0

与Flimm相同的结果。我在OS X上。对我而言,-L和-h适用于符号链接,但不适用于-e或-f。 – pauljm 2014-04-14 20:43:04

+0

@Flimm,所以如果我只想测试一个文件名是否被采用(不管是否存在目标文件或符号链接),最好的方法是什么?显然-e不行 – dragonxlwang 2016-02-28 20:34:22

12

您可以检查一个符号链接的存在,它不与破:

[ -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 
3

有关使用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 
相关问题