Friday, December 31, 2004

Shell Script - determine the directory where script is run from

>On 2004-11-08, Petterson Mikael wrote:
>
>>>> How can I determine the directory where my script is run from.
>>>> I need to use that to assign a variable $MY_HOME. It will be used when
>>>> I call files that are in the same directory or subdirectory to my
>>>> executing script.
>
>>
>> Maybe this one?
>> #v
>> MY_HOME=`which $0`
>> #v-


which is a command to be avoided. It's not builtin the shell
(except in tcsh and zsh).
Depending on the implementation, it may have nasty side effects
such as sourcing a ~/.cshrc in your home directory...

The POSIX command to find a command in $PATH is "command -v --"
But note that the command above would only be valid in bogus
versions of ksh (not pdksh nor recent versions of ksh93). The
shell is not supposed to look for the command in $PATH (if it
contains no slash and there's no such file in the current
directory, the shell may look it up in $PATH as do bash and the
fixed versions of ksh93, but that means it doesn't apply to
scripts run with the she-bang mechanism).

Note that $0 may be like ../foo.sh. So you'd need to do a get
the full directory (using cd -P ... && pwd -P)

For POSIX shells (bash/pdksh/zsh/BSDs sh...)

PROG_DIR=$(
prog=$0
[ -e "$prog" ] || prog=$(command -v -- "$0") # for "sh foo"
# where there's
# no foo in cwd
cd -P -- "$(dirname -- "$prog")" && pwd -P
)

For /broken/ versions of ksh (most):

PROG_DIR=$(
prog=$(command -v -- "$0")
cd -P -- "$(dirname -- "$prog")" && pwd -P
)

Note that both are generally equivalent. They may be different
in cases that seldom occur in real life.


____________________________________________

If you mean the current working directory, then it's $(pwd -P),
if you mean the path to the script when it was run, then it's
(assuming a POSIX shell):

$(cd -P -- "$(dirname -- "$0")" && pwd -P)

with ksh up to recent versions of ksh93:

$(cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P)

(but be sure you use that before any command that would modify
PATH or the current working directory in your script).

No comments: