Shell Scripts on Ubuntu
Posted October 1, 2010on:
It has been a long time that I have written about any technical details or new knowledge recently gained on this blog. One reason is that I have started using personal Wiki pages to document the accumulation of my own tech knowledge. Another reason is that I have been so absorbed in working that except working anything else is considered a waste of time and not even time to stop and consider what I have learned time and again.
Luckily this has changed. I spent nearly a full day today to write a shell script that can hook up with my own pre-commit hooks for svn. Along the way, I discovered useful bits on writing a shell script faster.
1. Number one discovery of the day: how to debug shell scripts. Change the shebang line from #!/bin/sh to #!/bin/sh -x will do the trick.
2. On Ubuntu, /bin/sh, by default, links to dash, which is a supposedly POSIX-compliant shell interpreter for bash. Unfortunately dash still has bugs which makes it not exactly POSIX compliant. So if your script starts complaining about ‘unexpected operator’, consider using bash directly instead of the symlinked dash. That is, change the shebang line from #!/bin/sh to #!/bin/bash
3. if [ $transaction == ” ] complains about unitary operator needed. this is because if $transaction is empty string, it will vanish completely and leave the interpreter looking for another input parameter. use “” to wrap around $transaction will fix it.
4. on a similar note, spaces after [ and before ] for a condition are not optional. dash will complain about weird things while bash will tell you there is a missing ].
5. I don’t understand why most tutorials online says ‘if  then … else … fi’ or ‘ if  then … elif … else .. fi’ are acceptable if statements. In reality, for the latter case, it is actually ‘if  then … elif  then … else … fi’