Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

2 Answers 2

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

 
discard

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.