How to tell if I'm actually in a symlink location from command line?
Depending on how your pwd
command is configured, it may default to showing the logical working directory (output by pwd -L
) which would show the symlink location, or the physical working directory (output by pwd -P
) which ignores the symlink and shows the "real" directory.
For complete information you can do
file "$(pwd -L)"
Inside a symlink, this will return
/path/of/symlink: symbolic link to /path/of/real/directory
Note that pwd
is actually a shell built-in. Depending on your shell and its configuration, results may change. For a more portable solution, you should use /bin/pwd
. Snippet from manual page:
NAME
pwd - print name of current/working directory
SYNOPSIS
pwd [OPTION]...
DESCRIPTION
Print the full filename of the current working directory.
-L, --logical
use PWD from environment, even if it contains symlinks
-P, --physical
avoid all symlinks
--help display this help and exit
--version
output version information and exit
If no option is specified, -P is assumed.
NOTE: your shell may have its own version of pwd, which usually supersedes the version described here. Please refer to your shell's documentation for
details about the options it supports.
In general, you can resolve the full canonical path of any file/directory using readlink -f
. readlink -f .
works similar to pwd -P
.
You really are in /home/cpm135/public_html/class
-- that's the only correct answer to the question of "what's my current working directory".
When you refer to /var/lib/class
... that's not really about where you are, but more about what path you used to get there.
When you run /bin/pwd
, it figures out your current working directory by looking at the . and .. directories (the ones listed at the top of ls -la
), working out which directory in .. matches up with . and then working backwards until .. and . refer to the same directory. Once it's done all that, it knows what your current working directory is.
When you run the pwd
shell built-in, it doesn't follow this procedure (though it might do some of it if needed) -- instead, it remembers the path that you took to get here. So each time you do a cd
command, your shell remembers that as part of the path to get where you are now, and pwd
prints out what it has calculated based on all the cd
commands you've done -- which may or may not be your actual working directory.
Things can get really weird when you do a ln -s . foo
and keep cd
ing into foo -- /bin/pwd
will say you're still in the same directory, but the shell builtin pwd
will say you're in /foo/foo/foo/foo/foo/foo
-- even though no such directory even really exists. (That said -- you probably can cd
into it.)
Another source of confusion there is if directories are renamed. /bin/pwd
will then pick up on the change immediately, but the built-in pwd
won't until you do something that tells it that the old directory name doesn't matter.