17

Can someone explain how to test for a bash shell script?

For example i've got a .sh file with this code in it...

#!/bin/sh

for file in *.txt; do
    mv "$file" "`basename $file .txt`.doc"
done

How do I write a test for it? Like in Java you've got unit testing where you write code like assertEquals to test the code gives the desired output.

4

3 Answers 3

18

Try this out: assert.sh

source "./assert.sh"

local expected actual
expected="Hello"
actual="World!"
assert_eq "$expected" "$actual" "not equivalent!"
# => x Hello == World :: not equivalent! 
Sign up to request clarification or add additional context in comments.

Comments

11

You can do asserts in Bash. Check out this from the Advanced Bash-Scripting Guide:

http://tldp.org/LDP/abs/html/debugging.html#ASSERT

2 Comments

Please don't encourage the ABS as a reference -- as a rule, it's undermaintained, and makes a habit of showcasing bad-practice examples. The Wooledge wiki and the bash-hackers wiki (and of course the official manual) are much better resources.
@CharlesDuffy Generally good advice but not very helpful in this case as you haven't pointed at an alternative and ABS does at least provide an assert script whereas neither the Wooledge wiki (mywiki.wooledge.org/…) nor the Bash Hackers Wiki (wiki-dev.bash-hackers.org/start?do=search&id=assert) contain any discussion of assertions at all.
4

I'd add an echo in front of the mv to verify that the right commands are being created, for starters. (Always a good idea with commands that make possibly difficult to undo changes.)

Some possibly useful resources:

2 Comments

Alright, thanks. But i'm trying to create a .sh file that test that whole code.
@Mr Teeth: added some links above. That said, shell scripts are a little harder to unit test effectively because almost everything boils down to invoking external commands. It's almost more sensible and useful to test those commands, and test the script itself by stubbing external modifications out with echo, as a result.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.