Quantcast
Viewing latest article 1
Browse Latest Browse All 46

Answer by David P. Chassin for How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

I use the single line

(cd ${FILENAME%/*}; pwd)

However, this can only be used when $FILENAME has a leading path of any kind (relative or absolute) that actually exists. If there is no leading path at all, then the answer is simply $PWD. If the leading path does not exist, then the answer may be indeterminate, otherwise and the answer is simply ${FILENAME%/*} if the path is absolute.

Putting this all together I would suggest using the following function

function abspath() {  # argument 1: file pathname (relative or absolute)  # returns: file pathname (absolute)  if [ "$1" == "${1##*/}" ]; then # no path at all    echo "$PWD"  elif [ "${1:0:1}" == "/" -a "${1/../}" == "$1" ]; then # strictly absolute path    echo "${1%/*}"  else # relative path (may fail if a needed folder is non-existent)    echo "$(cd ${1%/*}; pwd)"  fi}

Note also that this only work in bash and compatible shells. I don't believe the substitutions work in the simple shell sh.


Viewing latest article 1
Browse Latest Browse All 46

Trending Articles