[vox-tech] Identifying the directory that contains the currently running executable?

Ken Herron kherron+lugod at fmailbox.com
Fri Aug 27 11:31:34 PDT 2004


--On Friday, August 27, 2004 10:28:27 AM -0700 Ken Bloom 
<kabloom at ucdavis.edu> wrote:

> Is there a way to identify the directory that contains the currently
> running executable, so that I can programmatically refer to it?

Bill noted the entry in the /proc filesystem. For systems without /proc 
there's no simple way to get this. The program can examine argv[0], but 
that may contain only the program name without the directory path, in 
which case you would generally read the PATH environment variable and 
look for the program in each directory listed. It's also possible for 
argv[0] to contain an irrelevant or misleading string, so you shouldn't 
depend on it if security is an issue.

> Is there a way to identify the directory that contains the currently
> running script in bash?

$0 is the name of the script file. You can extract the directory portion 
with the dirname command. It might be a relative path, so if you need the 
absolute path you might have to combine it with $PWD.

> Are there ways to do this in other scripting languages (e.g. perl)?

Well, the interpreter must know where the script file is, so it's just a 
question of whether the interpreter makes the information available to 
the script. In the case of perl, it's also stored in the variable $0.

-- 
Ken Herron


More information about the vox-tech mailing list