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")"`</pre>
Then you can use the location of a partial filename, even if you change directories:
<pre>`**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
....