如何使用 bash 中的符号链接再次上下 cd?

Ati*_*liz 5 bash cd-command symlink

结构:

/base/
   +- somedir/
   +- symlink/  -> /some_other_dir
Run Code Online (Sandbox Code Playgroud)

此命令(除了我的 Makefile 之外)失败:

cd /base/symlink
ls ../somedir
Run Code Online (Sandbox Code Playgroud)

Bash 抱怨 ../somedir 不存在。同样,我在 some_other_dir 中引用 ../somedir 的 makefile 失败。但是, cd .. 可以按预期工作。我可以让我的 shell 对逻辑结构进行操作吗?

Sté*_*las 9

..是当前目录中的目录项。它是到上一级目录的硬链接。 /base/symlink/..实际上/some_other_dir/..与 , 是同一个文件/(除非some_other_dir它本身也是指向其他地方的符号链接)。

在大多数 shell 中,特殊cd处理..,即不是将其视为..目录条目,..而是由cd(而不是由系统的路径名解析)解释为删除一级目录。

例如,在 中cd a/b/..,shell 执行 achdir("a")而不是执行 a chdir("a/b/..")。要获得后者,您需要执行cd -P a/b/...

重要的是要意识到它仅适用于cd(并且仅在某些外壳中),(IMO,一个错误特征),不适用于lsvi其他任何东西(除非其他任何东西都是将这些路径传递给cdwithout的那些外壳的脚本-P)。

在那些弹cd这是否逻辑解释的..,该pwd内置和$PWD变量包含逻辑而不是当前目录的实际(物理)之一,即是一个与可能符号链接目录组件。同样,您可以使用pwd -P来获取物理工作目录。

现在,如果你想做

cd /A/b
anything-but-cd ../c
Run Code Online (Sandbox Code Playgroud)

实际上的意思是:

anything-but-cd /A/c
Run Code Online (Sandbox Code Playgroud)

无论是否/A/b是符号链接,您都可以改为:

anything-but-cd "$(dirname -- "$PWD")/c"
Run Code Online (Sandbox Code Playgroud)

或者

anything-but-cd "${PWD%/*}/c"
Run Code Online (Sandbox Code Playgroud)

或与zsh

anything-but-cd $PWD:h/c
Run Code Online (Sandbox Code Playgroud)

删除 3/*秒的结尾$PWD

anything-but-cd "${PWD%/*/*/*}/c" # POSIX
anything-but-cd $PWD:h:h:h/c      # zsh
Run Code Online (Sandbox Code Playgroud)