为什么这个bash -e和-L测试没有捕获到这个链接?

时间:2016-11-15 16:40:52

标签: bash

我有一个bash脚本,意图是幂等的。它创建符号链接,如果链接已经存在,它应该没问题。

这是一个摘录

    L="/var/me/foo"
    if [[ -e "$L" ]] && ! [[ -L "$L" ]];
    then
        echo "$L exists but is not a link."
        exit 1;
    elif [[ -e "$L" ]] && [[ -L "$L" ]];
    then
        echo "$L exists and is a link."
    else
        ln -s "/other/place" "$L" ||
        {
            echo "Could not chown ln -s for $L";
            exit 1;
        }
    fi

根据/var/me/foo,文件/other/place已经是指向ls -l的符号链接。

然而,当我运行此脚本时,ifelif分支输入,而是我们进入else并尝试{{1因为文件已经存在而失败。

为什么我的测试不起作用?

1 个答案:

答案 0 :(得分:3)

因为您只检查[ -L "$L" ]如果[ -e "$L" ]为真,并且[ -e "$L" ]对于指向不存在的目标的链接返回false,您不会检测指向的链接到不存在的地方。

以下逻辑更全面。

link=/var/me/foo
dest=/other/place
# because [[ ]] is in use, quotes are not mandatory
if [[ -L $link ]]; then
  echo "$link exists as a link, though its target may or may not exist" >&2
elif [[ -e $link ]]; then
  echo "$link exists but is not a link" >&2
  exit 1
else
  ln -s "$dest" "$link" || { echo "yadda yadda" >&2; exit 1; }
fi