Skip to content

Instantly share code, notes, and snippets.

@killwing
Created October 10, 2014 10:36
Show Gist options
  • Save killwing/5c50b25321648d6c1f17 to your computer and use it in GitHub Desktop.
Save killwing/5c50b25321648d6c1f17 to your computer and use it in GitHub Desktop.
cmd line options parser
#!/bin/bash
# for optional arguments: short - there can't be any spaces between the option and the argument
# long - the argument can only be passed by "="
# parse options
OPTIONS=$(getopt -o o::r:n -l optional::,required:,none -n "$0" -- "$@")
# check result
[ $? -ne 0 ] && exit 1
# set parsed options
eval set -- "$OPTIONS"
optional=""
required=""
none=0
# process
while true; do
case "$1" in
-o|--optional)
case "$2" in
"") optional='default'
shift 2 ;;
*) optional=$2
shift 2 ;;
esac ;;
-r|--required)
required=$2
shift 2 ;;
-n|--none)
none=1
shift ;;
--) shift
break ;;
*) echo "error!"
exit 1 ;;
esac
done
echo "none = $none"
echo "required = $required"
echo "optional = $optional"
echo "left = $@"
@killwing
Copy link
Author

@killwing
Copy link
Author

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