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:

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;;

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

Stolen fromĀ

Leave a Reply

Your email address will not be published. Required fields are marked *