Note that there are some explanatory texts on larger screens.

plurals
  1. POBash and Test-Driven Development
    primarykey
    data
    text
    <p>When writing more than a trivial script in bash, I often wonder how to make the code testable.</p> <p>It is typically hard to write tests for bash code, due to the fact that it is low on functions that take a value and return a value, and high on functions that check and set some aspect in the environment, modify the file-system, invoke a program, etc. - functions that depend on the environment or have side effects. Thus the setup and test code become much more complicated than the code they test.</p> <hr> <p>For example, consider a simple function to test:</p> <pre><code>function add_to_file() { local f=$1 cat &gt;&gt; $f sort -u $f -o $f } </code></pre> <p>Test code for this function might consist of:</p> <p>add_to_file.before:</p> <pre><code>foo bar baz </code></pre> <p>add_to_file.after:</p> <pre><code>bar baz foo qux </code></pre> <p>And test code:</p> <pre><code>function test_add_to_file() { cp add_to_file.{before,tmp} add_to_file add_to_file.tmp cmp add_to_file.{tmp,after} &amp;&amp; echo pass || echo fail rm add_to_file.tmp } </code></pre> <p>Here 5 lines of code are tested by 6 lines of test code and 7 lines of data.</p> <hr> <p>Now consider a slightly more complicated case:</p> <pre><code>function distribute() { local file=$1 ; shift local hosts=( "$@" ) for host in "${hosts[@]}" ; do rsync -ae ssh $file $host:$file done } </code></pre> <p>I can't even say how to start write a test for that...</p> <hr> <p>So, is there a good way to do TDD in bash scripts, or should I give up and put my efforts elsewhere?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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