Skip to content

Bash parameter parsing

Here is a code snippet I use for parameter parsing:

dohelp()
{
  echo "Example script"
  echo ""
 
  # Exit because you don't want the script to do anything after
  # displaying help, and do so with error, so that calling scripts won't think it succeeded
  exit 1
}
 
 
while [ -n "$*" ]; do
  flag="$1"
  value="$2"
 
  case "$flag" in
    "--one")
      one="$value"
      shift
    ;;
    "--two")
      two="$value"
      shift
    ;;
    "--pretend")
      pretend=true
    ;;
    "--help")
      dohelp
    ;;
    "--")
      break
    ;;
    *)
      echo -e "unknown option $flag\n"
      dohelp
    ;;
  esac
 
  shift
done


    No Comments ( Add comment / trackback )