3

Obviously I know about pwd and readlink, but is there a command to find out the real absolute path to the current directory (ie, resolving links and dots)?

Jonathan H
  • 2,303
  • 3
  • 20
  • 27

3 Answers3

5
pwd -P

(in any POSIX shell), is the command you're looking for.

-P is for physical (as opposed to logical (-L, the default) where pwd mostly dumps the content of $PWD (which the shell maintains based on the arguments you give to cd or pushd)).

$ ln -s . /tmp/here
$ cd /tmp/here/here
$ cd ../here/here
$ pwd
/tmp/here/here/here
$ pwd -P
/tmp
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
1

Use

$ env pwd

Or

$ /bin/pwd

Unless the variable POSIXLY_CORRECT is set, in which case you need to add -P.


The details:

The shell has a builtin called pwd which defaults to printing the value of shell's $PWD. In doing so, it may include logical paths (a default -L).

If you call the builtin with (-P) or use the external /bin/pwd:

$ ln -s . /tmp/here; cd /tmp/here/here/here

$ pwd
/tmp/here/here/here

$ pwd -P
/tmp

$ /bin/pwd 
/tmp

The reason is that the external /bin/pwd defaults to the -P option.
From info pwd:

this implementation uses -P' as the default unless thePOSIXLY_CORRECT' environment variable is set.

0

Using Python also works:

python -c "import os; print(os.path.realpath('.'))"
Jonathan H
  • 2,303
  • 3
  • 20
  • 27
  • Seems a little heavyweight to me to start a Python interpreter just to get the current path... – user May 27 '16 at 14:01
  • @MichaelKjörling :) Hence the question, but it turns out that RTFM was the answer to my question.. sorry about this! – Jonathan H May 27 '16 at 14:03
  • 1
    `getcwd()` from any language should work, no need to resort to `realpath`. The shell's interface to `getcwd()` is the `pwd` command, but by default, shells replace getcwd with a _fancy_ version that tries to give some information on how you got there, hence the need for `-P` there. Other languages don't have that problem, so you can use their `getcwd()` there like `os.getcwd()` for `python`. – Stéphane Chazelas May 27 '16 at 14:05