Search code examples
rustdirectorypathsymlinkworking-directory

How to get the current working directory in Rust if it is a symlink


If there is a directory /tmp/foo/bar and a directory /tmp/bar which is a link to /tmp/foo/bar made with ln -s /tmp/foo/bar /tmp/bar, then if the current working directory is /tmp/bar, Rust's std::env::current_dir will return /tmp/foo/bar instead of /tmp/bar?

Is there a way to get the current working directory in Rust without resolving symbolic links?


Solution

  • As per this GitHub issue, this is not really possible.

    For UNIX Rust just calls getcwd() and that behavior is documented in the POSIX spec, so it will be the same on all conforming implementations.

    From the linked spec:

    The pathname shall contain no components that are dot or dot-dot, or are symbolic links.

    A possible workaround is to look at the PWD environment variable, but it's dependent on the shell to set this, and it's not a requirement that shells do so. The executable may not have been invoked from a shell, either.