Get full path to file from argument

5.3k Views Asked by At

I am writing a shell script, and I am fairly new to it, but when the script gets run, the first first/second argument (depending on how you look at it) will be the file to load and execute. My question is, how would I get the location of the file based on where what directory myscript is run in?

myscript path/to/file.ext
myscript file.ext
myscript ../../file.ext

Basically I would like to get the path to the file that was passed in. How can that be done?

3

There are 3 best solutions below

2
On BEST ANSWER

This snippet will get you the full path of your script and any arguments:

DIR="$( cd "$( dirname "$i" )" && pwd )"

Replace $i with $0 to get the full path of your script (myscript). $1, $2, ... will get you the full paths of subsequence arguments.

1
On

In bash:

pathToFile=$(dirname $1)
fileName=$(basename $1)
scriptPath=$(dirname $0)
scriptName=$(basename $0)
currentPath=$(pwd)

In other shell, you can try to repalce $( and ) with ` (back quote)

1
On

The easiest way is to use realpath "$1". Despite being intended for use with symbolic links, it turns out that it works better than most other approaches for the general problem of making paths absolute.

On many systems, realpath might not be installed by default. Sometimes it is in its own package, sometimes it is in coreutils, etc.

Btw, this sort of question might be better suited on https://unix.stackexchange.com even though it's not off-topic here.