Converting a Relative Path to an Absolute Path in Bash

September 29th, 2007 by peasleer

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!


4 Responses to “Converting a Relative Path to an Absolute Path in Bash”

Feed for this Entry Trackback Address
  1. 1 foo

    This only works when the path in question already exists.

  2. 2 peasleer

    Very true. Post will be updated with a solution shortly.

  3. 3 Matt

    Thanks! That works well enough for me.

  4. 4 shanks

    Here’s a one-liner that works for me:
    #!/bin/bash
    echo “`cd \`dirname $1\`; pwd`/`basename $1`”

Leave a Reply