I need to run a script that access a file in the same path it is located.

For example: I have the script in /home/me/folder/script.sh, and this script will access the file /home/me/folder/myfile. As the file is in the same path of the script, I just use the name myfile, not the full path.

But if I run it from /tmp/, like:

/tmp$ /home/me/folder/script.sh

it gives me:

myfile: No such file or directory

So, how can I say in the script that the file is in the same path as the script itself?

  • Can you show what the usage of myfile is here? Mar 29, 2011 at 17:56
  • @Faheem Mitha: is just another script that my script.sh calls. Mar 29, 2011 at 18:01
  • Some reason you don't want to use the full path, or move both of these into your PATH? Mar 29, 2011 at 18:05
  • 1
    @Faheem Mitha: I want to be able to move this folder with the scripts to another place, maybe even another computer, without need to rewrite myfile's path. Mar 29, 2011 at 18:06

3 Answers 3


You can't know in all circumstances, but often (not always) when you run a script by path instead of letting the shell search $PATH, the path to the script will be in $0. You can then use dirname "$0" or ${0%/*} to get the path.


How about $(dirname "$0")/myfile?


I would normally do something like this at the head of my script:

SCRIPTDIR=$(dirname "$0")

Or, to get the full pathname to the script's directory (instead of a relative pathname):

SCRIPTDIR=$(cd $(dirname "$0") && pwd)

Then just reference ${SCRIPTDIR} where needed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .