当 location="~/.bashrc" 时 [ -L $location ] 或 [ -f $location ] 不准确

inaccurate [ -L $location ] or [ -f $location ] when location="~/.bashrc"

这是我第一次使用 bash 编程。作为第一个例子,我试图从我的 .bash_profile 中获取我的 .bashrc - 即使 ~/.bashrc 是一个符号 link。

.bash_profile:

if [ -f ~/.bashrc ] && ! [ -L ~/.bashrc ]
then
  # ~/.bashrc is a regular file. Source it!
  source ~/.bashrc
  echo "~/.bashrc found."
elif [ -L ~/.bashrc ]
then
  # ~/.bashrc is a symbolic link.

  # Recursivly follow symbolic links.
  location="~/.bashrc"
  while [ -L $location ]
  do
    # QUESTION: Control-Flow never reaches this point.

    # Follow link on macOS.
    location="$(readlink $path)"
  done

  # Check if final target is regular file. Source it!
  if [ -f $location ]
  then
    source $location
    echo "Symlink to .bashrc found."
  fi
else
  echo "No valid .bashrc found."
fi

这是我希望我的代码执行的操作:

作为测试,我为原始文件 .dotfiles/.bashrc 创建了一个符号 link ~/.bashrc。我的代码按预期进入 elif,但遗憾的是从未进入 while 循环的主体(如我所料,因为 ~/.bashrc 是符号 link)。

这是怎么回事?我认为 location 的变量赋值在某些方面是错误的。

替换:

location="$(readlink $path)"

有:

location="$(readlink $location)"

备注:

  1. 从未定义变量 path。我相信您打算将 readlink 应用于 location 而不是

  2. 如果你有 GNU readlink(在 Linux、自制软件等上可用),那么可以使用选项 -f 来消除循环的需要.

  3. 一般来说,shell 变量应该在双引号内引用,除非有人希望 shell 应用 分词波浪号扩展路径名扩展到变量的值。

    例如,在下一行中,我们想要 波浪号扩展。所以,~/ 需要在引号之外:

    location=~/.bashrc
    

    一旦完成,脚本中引用 location 的部分应该用双引号引起来。举个例子:

    location="$(readlink "$location")"
    

    这变得非常重要,例如,如果文件或路径名包含空格。

导致问题的原因:

location="~/.bashrc"

波浪号扩展不会出现在双引号中,也不会出现在

[ -L $location ]

两者皆有。

所以,不要在赋值中使用双引号,或者使用

location="$HOME/.bashrc"

或类似。