Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Can an executable know where it is stored?

For my open source project, I wrote a small bash script to automate some operations. The script lies at the root of the project and performs its tasks on all files below. People have the project files on their own computers, at their favorite path, so I can't just hardcode cd /home/nico/projects/theproject at the beginning of the script. I don't want to force people to manually cd to the project's directory everytime before executing either. I would like people to be able to use a Gnome shortcut to launch the script. To do so, the script needs to know where itself is stored.

share|improve this question
up vote 4 down vote accepted
#! /bin/bash
echo I am located in $(dirname "$0")
cd "$(dirname "$0")"

Note that this may be a relative path.

share|improve this answer
Works great, thanks for the trick! – Nicolas Raoul Jun 7 '11 at 6:52
#! /bin/bash
w=$(cd "$(dirname "$0")" && echo "$PWD")
echo I am located in "$w"

To build off of cjm's answer, the above will absolutize the path (by using a sub-shell to cd there and echo the $PWD)

share|improve this answer
Thanks! My script works fine with cjm's answer, but yours is interesting as well. – Nicolas Raoul Jun 8 '11 at 4:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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