15

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.

Mr Teeth
  • 1,269
  • 5
  • 19
  • 23

3 Answers3

17

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! 
Mark
  • 5,994
  • 5
  • 42
  • 55
10

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

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

Mark Nenadov
  • 6,421
  • 5
  • 24
  • 32
  • 3
    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. – Charles Duffy May 20 '17 at 20:07
  • 4
    @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 (https://mywiki.wooledge.org/FindPage?action=fullsearch&advancedsearch=1&and_terms=assert&or_terms=&not_terms=&mtime=&categories=&language=&mimetype=) nor the Bash Hackers Wiki (https://wiki-dev.bash-hackers.org/start?do=search&id=assert) contain any discussion of assertions at all. – Kevin Whitefoot Apr 11 '20 at 10:36
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:

geekosaur
  • 59,309
  • 11
  • 123
  • 114
  • Alright, thanks. But i'm trying to create a .sh file that test that whole code. – Mr Teeth Mar 21 '11 at 19:51
  • @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. – geekosaur Mar 21 '11 at 20:03