Skip to content

Instantly share code, notes, and snippets.

@gnilchee
Created March 18, 2016 00:41
Show Gist options
  • Save gnilchee/f8bb0478f81219b35efd to your computer and use it in GitHub Desktop.
Save gnilchee/f8bb0478f81219b35efd to your computer and use it in GitHub Desktop.
getopts for bash example with 4 inputs expected
#!/usr/bin/env bash
set -e
usage() {
echo "Usage: $0 -q {high|low} -e {event_ID}" >&2
exit 1
}
if [ $# -ne 4 ]; then
usage
fi
while getopts ":q:e:" opt; do
case "$opt" in
q)
IMG_QLTY=${OPTARG}
test "${IMG_QLTY}" = "high" || test "${IMG_QLTY}" = "low" || usage
;;
e)
EVENT_ID=${OPTARG}
[[ ${EVENT_ID} =~ ^[0-9]{5,}$ ]] || usage
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage
;;
esac
done
shift $((OPTIND-1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment