Expand a possible relative path in bash
MY_PATH=$(readlink -f $YOUR_ARG)
will resolve relative paths like "./"
and "../"
Consider this as well (source):
#!/bin/bashdir_resolve(){cd "$1" 2>/dev/null || return $? # cd to desired directory; if fail, quell any error messages but return exit statusecho "`pwd -P`" # output full, link-resolved path}# sample usageif abs_path="`dir_resolve \"$1\"`"thenecho "$1 resolves to $abs_path"echo pwd: `pwd` # function forks subshell, so working directory outside function is not affectedelseecho "Could not reach $1"fi
http://www.linuxquestions.org/questions/programming-9/bash-script-return-full-path-and-filename-680368/page3.html has the following
function abspath { if [[ -d "$1" ]] then pushd "$1" >/dev/null pwd popd >/dev/null elif [[ -e "$1" ]] then pushd "$(dirname "$1")" >/dev/null echo "$(pwd)/$(basename "$1")" popd >/dev/null else echo "$1" does not exist! >&2 return 127 fi}
which uses pushd
/popd
to get into a state where pwd
is useful.
Simple one-liner:
function abs_path { (cd "$(dirname '$1')" &>/dev/null && printf "%s/%s" "$PWD" "${1##*/}")}
Usage:
function do_something { local file=$(abs_path $1) printf "Absolute path to %s: %s\n" "$1" "$file"}do_something $HOME/path/to/some\ where
I am still trying to figure out how I can get it to be completely oblivious to whether the path exists or not (so it can be used when creating files as well).