Reputation: 9073
Sys.getcwd
seems to always return the "realpath" to the current directory, resolving symbolic links automatically.
For instance:
$ cd /tmp
$ mkdir real
$ ln -s real symlink
$ cd symlink
$ ocaml
# Unix.getcwd();;
- : string = "/tmp/real"
How can I get the "actual" cwd as seen by the shell, i.e. /tmp/symlink
, ideally without requiring external libraries?
Upvotes: 1
Views: 333
Reputation: 66813
I assume you're on a Unix-like system (Linux or similar).
Classically in Unix, the "actual" current directory is a specific open file in the file system, not a string. The method of getting a string representation of this directory requires a search through files in the containing directory, and their containing directory, and so on up to the root of the filesystem.
Due to hard and soft links, there can be more than one name for the same file. So there is no one result of this search process.
Furthermore, this is a pretty slow process. To avoid repeatedly searching, the shells tend to cache their idea of the name of the current directory. What you're asking for is to find out the contents of this cache in the shell, from some other process. This isn't really possible in general.
However many shells define an environment variable with the name of the current directory. So you might try this:
$ mkdir real
$ ln -s real symlink
$ cd symlink
$ ocaml
OCaml version 4.10.0
# Sys.getenv "PWD";;
- : string = "/Users/jeffsco/tryhofp/symlink"
As a side comment, it's perfectly possible for the shell to be wrong about the name of the current directory:
$ mkdir mydir
$ cd mydir
$ mv /Users/jeffsco/mydir /Users/jeffsco/otherdir
$ pwd
/Users/jeffsco/mydir
$ ls /Users/jeffsco/mydir
ls: /Users/jeffsco/mydir: No such file or directory
$ /bin/pwd
/Users/jeffsco/otherdir
The point here is that pwd
is a shell built-in that shows what the shell thinks is the name of the current directory. But the shell is wrong. The /bin/pwd
command does the search that I described above, and it gets the real name of the current directory.
Upvotes: 3