Tuesday, October 16, 2012

Bash programming tips - part 1

As industry standard all scripts that are not for single use should consist of at least 2 things - usage and configuration.


As a good practice I would expect the script when executed to show help in man format, although most of standard shell commands like ls, pwd execute immediately without requiring any parameters.


To start writing bash script we need editor (Kate, vim i.e.) and bash, which is a part of any modern Linux distribution.


Typical bash script looks something like:

#!/bin/bash

## Includes
#
source scripts/_config.sh

#
# Main
#

## Validate input
validate_input $@

# Settings
while [ $# -ne 0 ]; do
   case -o|--option)
         _TARGET="$1"
         shift
         ;;
      -h|--help)
         usage;
         exit 1
         ;;
      (--) usage; exit 1;;
      (-*) usage; exit 1;;
      (*)
          usage;
          exit 1;;
   esac
done

exit 0

Code above is pretty much self explanatory. Bash allows you to include external files into script and this is a good practice to keep code clean and readable. This is where you should put your configuration (at least if it is not trivial, so use your brains)

At the beginning of main section I usually put some sort of input validation (discussed in detail in later posts) to terminate script immediately if input is invalid. Next is parameter parsing either manually like above or with functions like getopts. Script the continues depending on selected options.






Post a Comment