What's the best way to check if two paths are equal in Bash? For example, given the directory structure
~/
Desktop/
Downloads/ (symlink to ~/Downloads)
Downloads/
photo.png
and assuming that the current directory is the home directory, all of the following would be equivalent:
./ and ~
~/Desktop and /home/you/Desktop
./Downloads and ~/Desktop/Downloads
./Downloads/photo.png and ~/Downloads/photo.png
Is there a native Bash way to do this?
Native bash way:
pwd -P
returns the physical directory irrespective of symlinks.Another way is to use
cd -P
, which will follow symlinks but leave you in the physical directory:You can use
realpath
. For example:Also take a look at a similar answer here: bash/fish command to print absolute path to a file
Bash's test commands have a
-ef
operator for this purposeetc...
If you have coreutils 8.15 or later installed, you have a
realpath
command that fully normalizes a path. It removes any.
and..
components, makes the path absolute, and resolves all symlinks. Thus:Methods based on resolving symlinks fail when there are other factors involved. For example, bind mounts. (Like
mount --bind /raid0/var-cache /var/cache
Using
find -samefile
is a good bet. That will compare filesystem and inode number.-samefile
is a GNU extension. Even on Linux, busybox find probably won't have it. GNU userspace and Linux kernel often go together, but you can have either without the other, and this question is only tagged Linux and bash.)e.g. on my system:
You can use
find -L
for cases where you want to follow symlinks in the final path component:Obviously this works for paths which refer to directories or any type of file, not just regular files. They all have inode numbers.
usage:
So
find -L
dereferences symlinks for-samefile
, as well as for the list of paths. So either or both can be symlinks.