问题
Assume I have the folders ~/a/b in my home folder, and the folder b contains a symbolic link to '..' named 'symlink'. Then I perform the following actions in bash:
hm@mach:~$ cd a/b/symlink
hm@mach:~/a/b/symlink$ pwd -P
/home/hm/a
hm@mach:~/a/b/symlink$ cd ..
hm@mach:~/a/b$ pwd -P
/home/hm/a/b
pwd -P prints the current working directory, dereferencing all symbolic links. Why is the working directory /home/hm/a/b at the end, and not /home/hm?
回答1:
bash
is being "friendly"; when you cd /into/a/symlink/
, the shell remembers the old location (in $OLDPWD
) and will use that directory when you cd ..
under the assumption that you want to return to the directory you were just in.
If you want to use the real ..
, then you must also use cd -P
:
The -P option says to use the physical directory
structure instead of following symbolic links (see
also the -P option to the set builtin command);
the -L option forces symbolic links to be followed.
$ cd
$ cd a/b/symlink
$ cd -P ..
$ pwd -P
/home/sarnold
$
回答2:
bash
keeps track of the logical current directory path, as shown in your prompt, and interprets things like cd ..
according to that. This makes things a little more consistent if you only use such paths in cd
(or pushd
), at the cost of unexpected things happening if you then expect the same thing to happen with paths in command arguments (or inside commands; emacs
and vim
have their own configurable rules for symlink handling, but most commands rely on the kernel to deal with it).
来源:https://stackoverflow.com/questions/10456784/behavior-of-cd-bash-on-symbolic-links