Home > All, Linux > Relative path to absolute path in a bash shell.

Relative path to absolute path in a bash shell.

There are many ways to convert a relative path to an absolute path which can be accessed regardless of the current working directory, particularly useful for scripting. Later, I may make a post to demonstrate the various ways, but the easiest way to do this is to use the readlink utility which comes bundled with just about every Linux distribution with the exception of Debian based systems which use realpath instead.

$ pwd
/media/usbdisk/bin

$ readlink -f ./../mnt/.Skype
/media/usbdisk/mnt/.Skype

When you use readlink in a script and assign a resulting path to a variable, you should add the n flag (-fn) to suppress the trailing newline.

As you might have noticed, I needed to use this in a script to launch Skype but specify that I want to use the data files on my usb key as opposed to the default ~/.Skype location. This however was not working with relative paths and Skype would crash with something like:

$ FatalAssert(*out_ptr != ‘.’ && !strstr(out_ptr, “../”) && !strstr(out_ptr, “..\\”))
FatalAssert(*out_ptr != ‘.’ && !strstr(out_ptr, “../”) && !strstr(out_ptr, “..\\”))

The moment I pass a real path to Skype’s –dbpath parameter, everything works as expected.