You're right to ask about symbolic links! $PWD will give you the path as you see it, which includes the symbolic link. To get the real path, you need to use readlink -f or realpath.
Here's how:
1. Using readlink -f:
readlink -f .
Explanation:
readlink: This command is designed to read the value of a symbolic link.
-f (or --canonicalize): This option tells readlink to follow all symbolic links in every component of the given path until it reaches the actual file or directory. It also resolves relative path components like . and ...
.: Represents the current directory.
2. Using realpath:
realpath .
Explanation:
realpath: This command is similar to readlink -f. It resolves symbolic links and returns the absolute, canonical path.
.: Represents the current directory.
Example:
Let's say you have a symbolic link:
lrwxrwxrwx 1 user user 10 Oct 26 10:00 mylink -> /path/to/real/directory
And you cd into mylink:
cd mylink
Now:
pwd will output: /path/to/real/directory (if the link was followed by cd) or /path/to/mylink (if cd didn't follow the link).
readlink -f . will always output: /path/to/real/directory
realpath . will always output: /path/to/real/directory
Which one to use?
realpath is generally preferred if it's available on your system. It's part of the GNU coreutils and is often more portable than readlink -f.
readlink -f is a good alternative if realpath isn't available. It's widely available on most Unix-like systems.
Getting the parent directory of the real path:
If you want the parent directory of the real path, you can combine these commands with dirname:
dirname "$(readlink -f .)"
or
dirname "$(realpath .)"
This will first resolve the symbolic link to the real path, and then extract the parent directory from that real path.
In summary, when dealing with symbolic links, always use readlink -f or realpath to get the actual path, rather than relying on $PWD. This will prevent unexpected behavior in your scripts.