Alex Rivera | Logout

Expand a possible relative path in bash

Asked 2011-08-19T19:39:48.807
106

As arguments to my script there are some file paths. Those can, of course, be relative (or contain ~). But for the functions I've written I need paths that are absolute, but do not have their symlinks resolved.

Is there any function for this?

Edit
Report

1 Answer

89

MY_PATH=$(readlink -f $YOUR_ARG) will resolve relative paths like "./" and "../"

Consider this as well (source):

#!/bin/bash
dir_resolve()
{
cd "$1" 2>/dev/null || return $?  # cd to desired directory; if fail, quell any error messages but return exit status
echo "`pwd -P`" # output full, link-resolved path
}

# sample usage
if abs_path="`dir_resolve \"$1\"`"
then
echo "$1 resolves to $abs_path"
echo pwd: `pwd` # function forks subshell, so working directory outside function is not affected
else
echo "Could not reach $1"
fi
answered 2011-08-19T20:01:52.903

Your Answer