Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a bash shell script [duplicate]

Tags:

bash

shell

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.

like image 391
Mr Teeth Avatar asked Mar 21 '11 19:03

Mr Teeth


3 Answers

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! 
like image 53
Mark Avatar answered Oct 20 '22 09:10

Mark


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

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

like image 32
Mark Nenadov Avatar answered Oct 20 '22 07:10

Mark Nenadov


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:

  • shUnit2 — xUnit framework for script unit testing
  • Bash IDE for Vim
  • Bash debugger
like image 45
geekosaur Avatar answered Oct 20 '22 09:10

geekosaur