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?

5 Answers

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."

3

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.

2

You can use:

realpath file.ext
7

From

This is the only way that is acceptable to me. Doesn't expand links like realpath and readlink and is the classical way of doing it that I've seen all over.

#! /bin/sh
echo "$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")"
1

to answer your question with what you use right now:

the alias expands at the position where you are typing right now. you typed:

% fp<SPACE>file.ext

this becomes

% echo `pwd`<SPACE>file.exe

you could use a function to avoid that:

function fp() { echo `pwd`/"$1"
}

you can use that as usual:

% fp file.ext
6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like