Skip to content
Snippets Groups Projects
Commit b8b27aac authored by nimrod's avatar nimrod
Browse files

New post on finding if a shell script is sourced or run.

parent 285e185f
No related branches found
No related tags found
No related merge requests found
Finding is a script sourced or not?
###################################
:date: 2016-02-29
:summary: How to find if a shell script is 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
outputing 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-comliant way (at least on my test machines, Debian with Bash and Dash
and KSH on OpenBSD). Here is an example usage:
.. code:: shell
#!/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 (:code:`$_`) 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 (:code:`$-`)
contain :code:`i` for interactive. This works when both marking the script as
executable and passing the name as a parameter to the shell.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment