| Måns Rullgård 2005-05-01, 6:21 pm |
| phil_gg04@treefic.com writes:
>
> This isn't easy. I generally do this:
>
> case $0 in
> /*) SCRIPT=$0 ;;
> ./*) SCRIPT="`pwd`/$0" ;;
> *) SCRIPT=`which $0` ;;
> esac
>
> SCRIPT_DIR=`dirname $SCRIPT`
>
> $0 contains the name of the script when it starts. The case considers
> three possibilites: it could be an absolute pathname, e.g.
> "/usr/bin/foo", or a relative pathname ("./foo"), or a bare name in
> which case you can look it up in the path.
>
> I think there are some problem cases, but I don't remember them now.
> Can anyone spot anything obvious?
A relative path doesn't necessarily start with "./". It could just as
well be something like "foo/bar/script", or "../foo/script". A better
(and simpler) solution is to always use "which":
SCRIPT="`which \"$0\"`"
SCRIPT_DIR="`dirname \"$SCRIPT\"`"
Be sure to quote everything properly, or you might be in for a
surprise. If your shell supports it, the $(command) construct makes
quoting a bit less messy.
> I would certainly treat the result that it gives you as "untrusted"
> from a security point of view, i.e. as if the user had entered it
> themselves.
The user can pretty much set it to whatever he wants:
ln -s script problem-causing-name
../problem-causing-name
--
Måns Rullgård
mru@inprovide.com
|