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? – Faheem Mitha Mar 29 '11 at 17:56
  • @Faheem Mitha: is just another script that my script.sh calls. – Tom Brito Mar 29 '11 at 18:01
  • Some reason you don't want to use the full path, or move both of these into your PATH? – Faheem Mitha Mar 29 '11 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. – Tom Brito Mar 29 '11 at 18:06

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


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.


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.

Your Answer

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

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