4

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 Answers 3

7

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.

1
  • Thanks, I usually script this myself, but good to learn about this tool Commented Mar 10, 2023 at 9:36
6

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.

2
  • I feel like this fails for paths with relative paths with preceding parent directories, e.g. ../<path>. If I'm in /home/dir1/, then typing in (cd "$(dirname "../dir2/")" && pwd) returns /home/ instead of /home/dir2/.
    – yuyu5
    Commented Mar 9, 2021 at 22:43
  • UPDATE: Nevermind Tuan, you are correct. I wasn't adding the required file name in my path when I was testing this, I was only testing directories alone.
    – yuyu5
    Commented Mar 9, 2021 at 23:03
5

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
  • This will help me get the file basename which I will need too Commented Jun 23, 2015 at 3:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.