How to get the full path of a file in bash?

I would like an easy way to get the full path to a file. I currently type this:

echo `pwd`/file.ext

Trying to shorten it, I made a bash alias:

alias fp='echo `pwd`/'

But now if I type fp file.ext, there is a space that appears between the / and the file.ext.

Does such a command already exist, and I am missing it? If not, how would I go about creating such an alias or function in bash?


Solution 1:

On linux systems, you should have readlink from the GNU coreutils project installed and can do this:

readlink -f file.ext

Debian/ubuntu systems may have the realpath utility installed which "provides mostly the same functionality as /bin/readlink -f in the coreutils package."

Solution 2:

Instead of the pwd command, use the PWD variable (it's in POSIX as well):

fp () {
  case "$1" in
    /*) printf '%s\n' "$1";;
    *) printf '%s\n' "$PWD/$1";;
  esac
}

If you need to support Windows, recognizing absolute paths will be more complicated as each port of unix tools has its own rules for translating file paths. With Cygwin, use the cygpath utility.