How do I change my pwd to the real path of a symlinked directory?

LinuxSymlinkPwd

Linux Problem Overview


Here's a rather elementary *nix question:

Given the following symlink creation:

ln -s /usr/local/projects/myproject/ myproject

... from my home directory /home/jvf/, entering the myproject symlink gives me a pwd /home/jfv/myproject/. Now, I would like to enter the parent directory of the directory I've symlinked to, but the cd .. command will only bring me back to my home directory /home/jfv/. Is there anyway to escape the symlink trail that I've entered, and instead have a pwd equal to the actual path of the myproject directory. That is, changing my pwd from /home/jfv/myproject/ into /usr/local/projects/myproject/?

Thanks :)

Linux Solutions


Solution 1 - Linux

Just use -P (physical) flag:

pwd -P

cd -P ..

Solution 2 - Linux

If you do the following you should be OK.

  1. First you follow your symlink:

    [jfv@localhost ~]$ cd myproject

  2. Now you execute the following command:

    [jfv@localhost myproject]$ cd -P ./

  3. Now, you can check your location and you will see that you are on the physical directory

    [jfv@localhost myproject]$ pwd

The output will be as follows:

/usr/local/projects/myproject

Now, everything you do will be local and not on the symlink.

Solution 3 - Linux

Programmatically, you would do this with the getcwd library function:

#include <unistd.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    char buf[1024*1024L];
    char *cwd;
    
    cwd = getcwd(buf, sizeof buf);
    if (cwd == NULL) {
        perror("getcwd");
        return 1;
    }
    printf("%s\n", cwd);
    return 0;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohan Fredrik VarenView Question on Stackoverflow
Solution 1 - LinuxCfrView Answer on Stackoverflow
Solution 2 - LinuxDrupalFeverView Answer on Stackoverflow
Solution 3 - Linuxuser25148View Answer on Stackoverflow