如何从命令行判断我是否实际上位于符号链接位置?

Oli*_*ams 33 shell cd-command symlink working-directory

假设我有一个文件夹:

cd /home/cpm135/public_html
Run Code Online (Sandbox Code Playgroud)

并建立一个符号链接

ln -s /var/lib/class .
Run Code Online (Sandbox Code Playgroud)

后来,我在那个目录中:

cd /home/cpm135/public_html/class
Run Code Online (Sandbox Code Playgroud)

pwd是要告诉我,我在/home/cpm135/public_html/class

有什么方法可以知道我“真的”在/var/lib/class吗?谢谢

Zan*_*nna 56

根据您的pwd命令的配置方式,它可能默认显示逻辑工作目录(由 输出pwd -L),它将显示符号链接位置,或物理工作目录(由 输出pwd -P),它忽略符号链接并显示“真实”目录。

有关完整的信息,您可以这样做

file "$(pwd -L)"
Run Code Online (Sandbox Code Playgroud)

在符号链接内,这将返回

/path/of/symlink: symbolic link to /path/of/real/directory
Run Code Online (Sandbox Code Playgroud)

  • 要回答标题中的问题,只需使用`test "$(pwd -L)" = "$(pwd -P)" && echo No symlinks`(或用`|| echo Symlinks 替换`&& echo No symlinks` `)。 (6认同)
  • 是的,“-P”标志正是我所需要的。谢谢 (2认同)

Gow*_*ham 17

请注意,这pwd实际上是一个内置的外壳。根据您的外壳及其配置,结果可能会发生变化。对于更便携的解决方案,您应该使用/bin/pwd. 手册页的片段:

NAME
       pwd - print name of current/working directory

SYNOPSIS
       pwd [OPTION]...

DESCRIPTION
       Print the full filename of the current working directory.

       -L, --logical
              use PWD from environment, even if it contains symlinks

       -P, --physical
              avoid all symlinks

       --help display this help and exit

       --version
              output version information and exit

       If no option is specified, -P is assumed.

       NOTE:  your  shell  may  have  its  own  version of pwd, which usually supersedes the version described here.  Please refer to your shell's documentation for
       details about the options it supports.
Run Code Online (Sandbox Code Playgroud)

通常,您可以使用readlink -f. readlink -f .工作类似于pwd -P.

  • 尽管我已经学会了“readlink -f”并非在所有 Unices 上都可用(例如在 OS-X 上不可用)的艰难方法 (2认同)