Skip to content

Instantly share code, notes, and snippets.

@jlintz
Created February 2, 2012 02:46
Show Gist options
  • Save jlintz/1721082 to your computer and use it in GitHub Desktop.
Save jlintz/1721082 to your computer and use it in GitHub Desktop.
parsing command line arguments in bash
function usage() {
echo ".$0 --argument=foo --argument-two=bar"
exit 1
}
while [ "$1" != "" ]; do
param=${1%=*}
value=${1#*=}
case $param in
--argument) argument=$value
;;
--argument-two) argument_two=$value
;;
* ) usage
;;
esac
shift
done
@nmilford
Copy link

nmilford commented Feb 2, 2012

Y U NO GETOPT?

usage="usage: $0 -a <arg A> -b <arg B>"

while getopts ":a:b:" options; do
   case $options in
      a ) argA=$OPTARG;;
      b ) argB=$OPTARG;;
      * ) echo $usage
            exit 1;;
   esac
done

if [[ -z $argA ]] || [[ -z $argB ]]; then
   echo $usage
   exit 1
fi

@jehiah
Copy link

jehiah commented May 25, 2012

@nmilford the pain of getopts is that single variable options are cryptic. They work great for tools like grep that are used by a million people, but they are absolutely terrible for custom scripts. long args foster clear and descriptive (translation: useful) shell scripts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment