开发者

What's the difference between unix built-in `pwd` command and it's $PWD environment variable?

开发者 https://www.devze.com 2023-01-29 04:17 出处:网络
Here\'s the case. I have a directory call :- %/home/myname/ I did a soft link in that directory:- %cd /home/myname/

Here's the case. I have a directory call :- %/home/myname/

I did a soft link in that directory:- %cd /home/myname/ %ln -s /home/others/ .

Now, I cd into others/ from /home/myname/ Here's the interesting part.

When I did a unix built-in pwd command, i get the ORIGINAL path name:- %/home/others/

But when i echo the $PWD environment variable, i get the link path name:- %/home/myname/others/

Why is that开发者_开发百科 so?


/var# ls -l
lrwxrwxrwx  1 root root   10 Aug 22 13:21 mail -> spool/mail
drwxr-xr-x  2 root root 4096 Jul  1 20:58 opt
drwxr-xr-x 22 root root 4096 Dec  5 17:38 run
drwxr-xr-x 12 root root 4096 Aug 22 13:21 spool
drwxrwxrwt 14 root root 4096 Dec  6 02:46 tmp
/var# cd mail
/var/mail# echo $PWD
/var/mail

/var/mail# pwd
/var/mail

/var/mail# /bin/pwd
/var/spool/mail

In other words, using $PWD is sufficient, because pwd might not give you better results (for any definition of better) anyway.

Why that is? /bin/pwd uses OS-specific calls to determine the current working directory - and in case of Linux, the kernel only keeps the resolved directory (see /proc/self/cwd), whereas the shell's pwds contain what the shell thinks it is in.


The difference between the /bin/pwd external command and the built-in is that the external command doesn't know what set of cd operations got you there and therefore doesn't pretend that your current directory is somewhere down a chain of symlinks; it gives you the direct path from root to your current directory, rather like the realpath() function would.

See set -o physical in bash.


/bin/pwd uses OS-specific calls to determine the current working directory.

you have an illustration of that with Git 2.34 (Q4 2021), which had to replace $(pwd) with $PWD, and explained why.

See commit f6a5af0 (24 Aug 2021) by Johannes Sixt (j6t).
(Merged by Junio C Hamano -- gitster -- in commit e18f4de, 08 Sep 2021)

t9001: PATH must not use Windows-style paths

Signed-off-by: Johannes Sixt

On Windows, $(pwd) returns a drive-letter style path C:/foo, while $PWD contains a POSIX style /c/foo path.
When we want to interpolate the current directory in the PATH variable, we must not use the C:/foo style, because the meaning of the colon is ambiguous.
Use the POSIX style.

0

精彩评论

暂无评论...
验证码 换一张
取 消