From b8b27aac64e80790f1400cd88a25df303e564e91 Mon Sep 17 00:00:00 2001 From: Adar Nimrod <nimrod@shore.co.il> Date: Wed, 2 Mar 2016 12:15:36 +0200 Subject: [PATCH] New post on finding if a shell script is sourced or run. --- content/sourced_or_not.rst | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 content/sourced_or_not.rst diff --git a/content/sourced_or_not.rst b/content/sourced_or_not.rst new file mode 100644 index 0000000..fe7e354 --- /dev/null +++ b/content/sourced_or_not.rst @@ -0,0 +1,32 @@ +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. -- GitLab