Converting a Relative Path to an Absolute Path in Bash
This really shouldn’t have taken me as long as it did to figure this out, but it was a big enough of an annoyance that I decided to share it.
How to convert a relative path to an absolute path in linux/unix/bash script:
#!/bin/bash
# Assume parameter passed in is a relative path to a directory.
# For brevity, we won't do argument type or length checking.
echo "Absolute path: `cd $1; pwd`"
For those unaware, you don’t have to ‘cd -’ because the backticks perform command substitution and don’t modify the working directory of the script.
EDIT: Anonymous poster ‘foo’ left a comment mentioning that this only works if the path destination already exists, which is indeed the case. This isn’t at all elegant, but it is the ‘two minute hack’ version I could immediately come up with. The result only works if you have permission to write where the path should go, meaning *yes,* there will be a version three of this script when I have more time:
#!/bin/bash # Alright, this time we'll do parameter checking. if [ $# -eq 0 ]; then echo "Usage: $0" exit 1 fi if [ -d $1 ]; then # Paramater is an existing directory. Print it using the method in the script above. echo "Absolute path: `cd $1; pwd`" elif [[ -e $1 && ! -d $1 ]]; then # File already exists and isn't a directory. Be more safe with the conversion. mkdir $1$$ 2> /dev/null if[ $? -ne 0 ]; then echo "We cannot conver this path without write permissions to the path's destination." exit 1 fi # I don't want to escape the quotes. This is already ugly, anyway. dirName=`cd $1$$; pwd | awk -F"$$" {'print $1'}` echo "Absolute path: $dirName" rm -r $1$$ else # File doesn't exist, begin unelegant conversion mkdir $1 2> /dev/null if [ $? -ne 0 ]; then echo "We cannot convert this path without write permissions to the path's destination." exit 1 fi echo "Absolute path: `cd $1; pwd`" rm -r $1 fi
Secondary notes: I really wrote this on the spot in a couple minutes, directly into this blog post. It is untested, and very ugly. I promise to post something better soon!
This only works when the path in question already exists.
Oct 19th, 2007 at 5:43 pm
Very true. Post will be updated with a solution shortly.
Oct 22nd, 2007 at 10:59 pm
Thanks! That works well enough for me.
Oct 26th, 2007 at 4:04 am
Here’s a one-liner that works for me:
#!/bin/bash
echo “`cd \`dirname $1\`; pwd`/`basename $1`”
Oct 30th, 2007 at 5:48 pm