Wednesday, October 17, 2012

Bash programming tips - part 5

Combining parts 1, 2,3 and 4 we almost have a script. Now to parameter parsing. There are more than one way to parse input parameters. You should check this post for excellent tutorial on parameters parsing. I will just discus my implementation. Now I will repost the snippet from first part.

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

As shown in code above we are looping trough the script parameters one by one, until there are none left. We are matching the parameter to the expected options (-o for example) and shifting the parameter value if option demands it. We display usage if we have unexpected option. With slight modification we can support multiple values for single parameter. I prefer shifting over i.e. getopts because this way I can support long version options (i.e. --help), but that is the matter of preference. This version does not support white spaces in parameter values.

Post a Comment