shellshposixbusybox

Get path of currently executing shell script run with busybox


In ConTeXt standalone, the file tex/setuptex contains code that needs the current path of tex/setuptex (which is usually e.g. $HOME/context, /opt/context, etc.). The code looks like this:

# this resolves to path of the setuptex script
# We use $0 for determine the path to the script, except for:
# * bash where $0 always is bash; here we use BASH_SOURCE
# * ksh93 where we use ${.sh.file}
# Thanks to Vasile Gaburici and Alessandro Perucchi for reporting this
# * http://www.ntg.nl/pipermail/ntg-context/2008/033953.html
# * http://www.ntg.nl/pipermail/ntg-context/2012/068658.html
if [ z"$BASH_SOURCE" != z ]; then
        SCRIPTPATH="$BASH_SOURCE"
elif [ z"$KSH_VERSION" != z ]; then
        SCRIPTPATH="${.sh.file}"
else
        SCRIPTPATH="$0"
fi

One usually runs this to update the current environment with an assortment of environment variables needed to run ConTeXt, with . path/tex/setuptex.

In BusyBox (on e.g. Alpine Linux), the $SCRIPTPATH is /, and it's not apparent what the correct way to get the path would be. Adding this line to the script:

echo "SCRIPTPATH $0 : $1 : $2"

yields:

SCRIPTPATH sh : :

Similarly env yields nothing with setuptex.

So I'm not certain where to start.

How does one replicate the *sh functionality one ordinarily uses to obtain the path of the currently executing script?


Solution

  • From Henri Menke (by email) -

    Standard POSIX sh has no way to reliably detect sourced invocation of a script. BusyBox uses POSIX sh underneath and thus suffers from the same limitation. See StackOverflow for detail: how to get script directory in POSIX sh?