Note that there are some explanatory texts on larger screens.

plurals
  1. POImporting functions from a shell script
    primarykey
    data
    text
    <p>I have a shell script that I would like to test with shUnit. The script (and all the functions) are in a single file since it makes installation much easier.</p> <p>Example for <code>script.sh</code></p> <pre><code>#!/bin/sh foo () { ... } bar () { ... } code </code></pre> <p>I wanted to write a second file (that does not need to be distributed and installed) to test the functions defined in <code>script.sh</code></p> <p>Something like <code>run_tests.sh</code></p> <pre><code>#!/bin/sh . script.sh # Unit tests </code></pre> <p>Now the problem lies in the <code>.</code> (or <code>source</code> in Bash). It does not only parse function definitions but also executes the code in the script.</p> <p>Since the script with no arguments does nothing bad I could</p> <pre><code>. script.sh &gt; /dev/null 2&gt;&amp;1 </code></pre> <p>but I was wandering if there is a better way to achieve my goal.</p> <p><strong>Edit</strong></p> <p>My proposed workaround does not work in the case the sourced script calls <code>exit</code> so I have to trap the exit</p> <pre><code>#!/bin/sh trap run_tests ERR EXIT run_tests() { ... } . script.sh </code></pre> <p>The <code>run_tests</code> function is called but as soon as I redirect the output of the source command the functions in the script are not parsed and are not available in the trap handler</p> <p>This works but I get the output of <code>script.sh</code>:</p> <pre><code>#!/bin/sh trap run_tests ERR EXIT run_tests() { function_defined_in_script_sh } . script.sh </code></pre> <p>This does not print the output but I get an error that the function is not defined:</p> <pre><code>#!/bin/sh trap run_tests ERR EXIT run_tests() { function_defined_in_script_sh } . script.sh | grep OUTPUT_THAT_DOES_NOT_EXISTS </code></pre> <p>This does not print the output and the <code>run_tests</code> trap handler is not called at all:</p> <pre><code>#!/bin/sh trap run_tests ERR EXIT run_tests() { function_defined_in_script_sh } . script.sh &gt; /dev/null </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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