Feb 29, 2016

Finding is a script sourced or not?

I've recently written a shell script that contained several functions and I wanted to support 2 usage methods. The first is quite regular, marking it as an executable and running it. The second is to source the script and gain the functions declared. The problem is not actually performing any tasks (or outputting anything) if the script is being sourced. It took a bit of fiddling but I found a short one-liner to add at the top of the script that solves this in a POSIX-compliant way (at least on my test machines, Debian with Bash and Dash and KSH on OpenBSD). Here is an example usage:

#!/bin/sh -e
# Check if the script is being sourced or not.
[ "$_" != "$0" ] && expr "$-" : ".*i.*" > /dev/null && sourced=1

if [ "$sourced" ]
then
    echo Sourced
else
    echo Run
fi

The solution is using 2 heuristics. If the last argument ($_) if different from the command name (must be first command run, otherwise the last argument will be overwritten). The second is if the option flags ($-) contain i for interactive. This works when both marking the script as executable and passing the name as a parameter to the shell.