Hire me if you like: blake.irvin@gmail.com

Wednesday, April 14, 2010

Using Flags and Arguments in Bash

Here's a simple example script, showing how to deal with different inputs depending on the flag preceding them:


#!/bin/bash

USAGE="Usage: Enter a noun after either -p (polite) or -i (insulting)."

while getopts ":p:i:" OPTIONS; do
  case $OPTIONS in
    p ) polite=$OPTARG;;
    i ) insulting=$OPTARG;;
    h ) echo $USAGE;;
    \? ) echo $USAGE
         exit 1;;
    * ) echo $usage
          exit 1;;
  esac

if [ $polite ]
    then
        echo "Your $polite smells good."
fi

if [ $insulting ]
    then
        echo "Your $insulting smells bad."
fi


done

No comments:

Archive