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.

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?

share|improve this question
    
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
    
@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

3 Answers 3

up vote 7 down vote accepted

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

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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.