Monday, December 8, 2008

3 commandments for writing a shell script

When you are writing shell scripts which are going to be deployed in alien and possibly hostile environments, here are some commandments to be followed so avoid most common pitfalls which later make us feel stupid :

  1. Absolutely assume nothing. Even if the OS which your script is getting deployed is the exact same as the OS you tested the script on, absolutely assume nothing. For e.g. If you are using grep or ps, don't assume that they will be on $PATH and your script will automagically find them. Just fully qualify the exact path of the binary you are trying to use.
  2. Don't assume that $HOSTNAME will be available to the shell. Don't trust the sysadmin of the target Unix box. For all you know he would be a fathead.
  3. Never never use $0 to identify the script which is running. If the script is being run with full path and you are checking something against $0, the check is bound to fail.
  4. Tatoo it on your brain that in ksh '-eq' is for comparing numbers and '=' is for comparing strings. As soon as you forget this, all hell could break loose depending upon how critical is your application.