Re: Finding absolute path of a script from within
2008-03-14, 05:36(-07), Jeenu:
[...]
> where_am_i=$((cd $(dirname $0) && pwd))
>
> Or is there any other/easier way?
That's really an approximation.
where_am_i=$(
cd -P -- "$(dirname -- "$0")" && pwd -P
)
will work in most cases.
case where it may not work is if the script is started as:
sh myscript.sh
instead of just:
myscript.sh
and myscript.sh happens not to be in the current directory in
which case it's being looked up in $PATH. To work around that,
you can do something like:
where_am_i=$(
if [ -e "$0" ]; then
prog=$0
else
prog=$(command -v -- "$0") || exit
fi
cd -P -- "$(dirname -- "$prog")" && pwd -P
)
This may still be fooled if the script is not executable and
your shell is not standard compliant (like bash) and finds it in
$PATH. (sh myscript, if myscript doesn't exist in the current
directory is meant to search for an *executable* myscript in
$PATH, bash misses the "executable" requirement, and command -v
only reports executables).
It will also not work if the directory name ends in newline
characters.
--
Stéphane
|