Quantcast
Channel: How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)? - Stack Overflow
Viewing all articles
Browse latest Browse all 46

Answer by Alexander Klimetschek for How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

$
0
0

This relative path to absolute path converter shell function

  • requires no utilities (just cd and pwd)
  • works for directories and files
  • handles .. and .
  • handles spaces in dir or filenames
  • requires that file or directory exists
  • returns nothing if nothing exists at the given path
  • handles absolute paths as input (passes them through essentially)

Code:

function abspath() {    # generate absolute path from relative path    # $1     : relative filename    # return : absolute path    if [ -d "$1" ]; then        # dir        (cd "$1"; pwd)    elif [ -f "$1" ]; then        # file        if [[ $1 = /* ]]; then            echo "$1"        elif [[ $1 == */* ]]; then            echo "$(cd "${1%/*}"; pwd)/${1##*/}"        else            echo "$(pwd)/$1"        fi    fi}

Sample:

# assume inside /parent/curabspath file.txt        => /parent/cur/file.txtabspath .               => /parent/curabspath ..              => /parentabspath ../dir/file.txt => /parent/dir/file.txtabspath ../dir/../dir   => /parent/dir          # anything cd can handleabspath doesnotexist    =>                      # empty result if file/dir does not existabspath /file.txt       => /file.txt            # handle absolute path input

Note: This is based on the answers from nolan6000 and bsingh, but fixes the file case.

I also understand that the original question was about an existing command line utility. But since this seems to be THE question on stackoverflow for that including shell scripts that want to have minimal dependencies, I put this script solution here, so I can find it later :)


Viewing all articles
Browse latest Browse all 46

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>