Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does $PWD always equal $(realpath .)

Tags:

linux

bash

shell

Given

  • A modern Linux/UNIX/OSX (w/ realpath)
  • bash 4+ (even on OSX)

Is

"$PWD" == "$(realpath .)"

Always true?

like image 395
PythonNut Avatar asked Feb 12 '23 07:02

PythonNut


1 Answers

It's pretty easy to test that this is not always the case.

$ mkdir /tmp/realdir
$ cd /tmp/realdir
$ echo $PWD
/tmp/realdir
$ ln -s realdir /tmp/fakedir
$ cd /tmp/fakedir
$ echo $PWD
/tmp/fakedir
$ realpath .
/tmp/realdir

so no, $PWD is not always the same as $(realpath .).

The bash manual indicates that the PWD variable is set by the built-in cd command. the default behaviour of cd is:

symbolic links are followed by default or with the -L option

This means that if you cd into a symlink the variable gets resolved relative to the symlink, not relative to the physical path. You can change this behavior for a cd command by using the -P option. This will cause it to report the physical directory in the PWD variable:

$ cd -P /tmp/fakedir
$ echo $PWD
/tmp/realdir

You can change the default behavior of bash using the -P option:

$ set -P
$ cd /tmp/fakedir
$ echo $PWD
/tmp/realdir
$ set +P
$ cd /tmp/fakedir
$ echo $PWD
/tmp/fakedir

This is of course notwithstanding the fact that you can assign anything you want to the PWD variable after performing a cd and it takes that value:

$ cd /tmp/fakedir
$ PWD=/i/love/cake
$ echo $PWD
/i/love/cake

but that's not really what you were asking.

like image 102
Petesh Avatar answered Feb 15 '23 10:02

Petesh