Atom Feed SITE FEED   ADD TO GOOGLE READER

Canonical path of a file in Bash

In Java, it's pretty straightfoward to take any abstract pathname (such as ~/Desktop/regina.jpg) and convert it to it's canonical pathname, /Users/jessewilson/Desktop/regina.jpg. Sometimes I find myself needing this function when writing simple shell scripts in Bash, and Google Groups showed me how.

Save the following text to a file called canonicalize, add it to your $PATH, and chmod it so it's executable:
#!/bin/bash
cd -P -- "$(dirname -- "$1")" &&
printf '%s\n' "$(pwd -P)/$(basename -- "$1")"


Then you can use the location of a partial filename, even if you change directories:
chixdiglinux:jessewilson$ canonicalize ./bash_profile
/Users/jessewilson/.bash_profile
chixdiglinux:jessewilson$ export JESSES_PROFILE=`canonicalize ./bash_profile`
chixdiglinux:jessewilson$ cd ~kevinmaltby
chixdiglinux:kevinmaltby$ diff $JESSES_PROFILE ./bash_profile
....
Congrats, you're the first link on a Google search for "bash canonical path"!

On that note, there's a better way to do this:

readlink -f [FILE]

readlink is supposed to be used to "dereference" symbolic links, but it works just fine for normal paths. The -f flag displays the path even if the file itself doesn't exist.

Take a look at the man page for more information.
In bash there's an option you can pass to pwd to dereference symbolic links in the path.

help pwd:

pwd: pwd [-LP]
Print the current working directory. With the -P option, pwd prints
the physical directory, without any symbolic links; the -L option
makes pwd follow symbolic links.

You could use this if you need full canonicalization of a path:

cd ~/foo; pwd -P