Skip to content

Instantly share code, notes, and snippets.

@Kamilcuk
Created June 20, 2017 11:21
Show Gist options
  • Save Kamilcuk/4aaf7f4e9095212811535620f8f8106f to your computer and use it in GitHub Desktop.
Save Kamilcuk/4aaf7f4e9095212811535620f8f8106f to your computer and use it in GitHub Desktop.
Template getopt bash util-linux
#/bin/bash
set -ueo pipefail
usage() {
cat <<EOF
Usage: $0 [option] arg...
$0 -h
Options:
-a, --aflag set a flag
-p, --par NUM pass parameter par
-h show this text and exit
Examples:
$0 -a argument0
$0 --par 0 argument0
Written by Kamil Cukrowski (c) 2017. Under MIT License.
EOF
}
# getopt
if [ $# -eq 0 ]; then usage; exit 1; fi
args=$(getopt --name "$0" -o ap:h -- "$@")
eval set -- "$args"
FLAGA=false PAR=0
while true; do
case "${1/#-/}" in
a) FLAGA=true; ;;
p) PAR=$1; shift; ;;
h) usage; exit 0; ;;
-) shift; break; ;;
*) echo "Error parsing argument: $1"; exit 1; ;;
esac
shift
done
echo "FLAGA=$FLAGA"
echo "PAR=$PAR"
echo "args: $@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment