Data is stored somewhere

Shell Script – determine the directory where script is run from

nnnnn>On 2004-11-08, Petterson Mikael wrote:
n>
n>>>> How can I determine the directory where my script is run from.
n>>>> I need to use that to assign a variable $MY_HOME. It will be used when
n>>>> I call files that are in the same directory or subdirectory to my
n>>>> executing script.
n>
n>>
n>> Maybe this one?
n>> #v
n>> MY_HOME=`which $0`
n>> #v-
n
n
nwhich is a command to be avoided. It’s not builtin the shell
n(except in tcsh and zsh).
nDepending on the implementation, it may have nasty side effects
nsuch as sourcing a ~/.cshrc in your home directory…
n
nThe POSIX command to find a command in $PATH is “command -v –“
nBut note that the command above would only be valid in bogus
nversions of ksh (not pdksh nor recent versions of ksh93). The
nshell is not supposed to look for the command in $PATH (if it
ncontains no slash and there’s no such file in the current
ndirectory, the shell may look it up in $PATH as do bash and the
nfixed versions of ksh93, but that means it doesn’t apply to
nscripts run with the she-bang mechanism).
n
nNote that $0 may be like ../foo.sh. So you’d need to do a get
nthe full directory (using cd -P … && pwd -P)
n
nFor POSIX shells (bash/pdksh/zsh/BSDs sh…)
n
nPROG_DIR=$(
nprog=$0
n[ -e “$prog” ] || prog=$(command -v — “$0”) # for “sh foo”
n# where there’s
n# no foo in cwd
ncd -P — “$(dirname — “$prog”)” && pwd -P
n)
n
nFor /broken/ versions of ksh (most):
n
nPROG_DIR=$(
nprog=$(command -v — “$0”)
ncd -P — “$(dirname — “$prog”)” && pwd -P
n)
n
nNote that both are generally equivalent. They may be different
nin cases that seldom occur in real life.
n
n
n____________________________________________
n
nIf you mean the current working directory, then it’s $(pwd -P),
nif you mean the path to the script when it was run, then it’s
n(assuming a POSIX shell):
n
n$(cd -P — “$(dirname — “$0″)” && pwd -P)
n
nwith ksh up to recent versions of ksh93:
n
n$(cd -P — “$(dirname — “$(command -v — “$0″)”)” && pwd -P)
n
n(but be sure you use that before any command that would modify
nPATH or the current working directory in your script).


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *