Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Picked up this technique from Python, but the concept works just fine in bash or any other shell...</p> <p>The idea is that we turn the main code section of our script into a function. Then at the very end of the script, we put an 'if' statement that will only call that function if we executed the script but not if we sourced it. Then we explicitly call the script() function from our 'runtests' script which has sourced the 'script' script and thus contains all its functions.</p> <p>This relies on the fact that if we source the script, the bash-maintained environment variable <code>$0</code>, which is the name of the script being executed, will be the name of the <strong>calling</strong> (parent) script (<code>runtests</code> in this case), not the sourced script.</p> <p>(I've renamed <code>script.sh</code> to just <code>script</code> cause the <code>.sh</code> is redundant and confuses me. :-)</p> <p>Below are the two scripts. Some notes...</p> <ul> <li><code>$@</code> evaluates to all of the arguments passed to the function or script as individual strings. If instead, we used <code>$*</code>, all the arguments would be concatenated together into one string.</li> <li>The <code>RUNNING="$(basename $0)"</code> is required since <code>$0</code> always includes at least the current directory prefix as in <code>./script</code>.</li> <li>The test <code>if [[ "$RUNNING" == "script" ]]...</code>. is the magic that causes <code>script</code> to call the script() function only if <code>script</code> was run directly from the commandline.</li> </ul> <p><strong>script</strong></p> <pre><code>#!/bin/bash foo () { echo "foo()"; } bar () { echo "bar()"; } script () { ARG1=$1 ARG2=$2 # echo "Running '$RUNNING'..." echo "script() - all args: $@" echo "script() - ARG1: $ARG1" echo "script() - ARG2: $ARG2" # foo bar } RUNNING="$(basename $0)" if [[ "$RUNNING" == "script" ]] then script "$@" fi </code></pre> <p><strong>runtests</strong></p> <pre><code>#!/bin/bash source script # execute 'script' function in sourced file 'script' script arg1 arg2 arg3 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload