Skip to content

Instantly share code, notes, and snippets.

@taskie
Last active October 28, 2018 18:01
Show Gist options
  • Save taskie/ec8f89b0191bfe1bb8aa3e1f51da0896 to your computer and use it in GitHub Desktop.
Save taskie/ec8f89b0191bfe1bb8aa3e1f51da0896 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# for GNU bash 3.x on Linux
declare PROGRAM_NAME="$(basename "$0")"
declare PROGRAM_DIR="$(realpath "$(dirname "$0")")"
function usage () {
cat <<EOF
${PROGRAM_NAME} - some nice program
Usage:
${PROGRAM_NAME} [-o FILE] [-f] [-v] FILE...
Options:
-o, --output FILE
-f, --force
-F, --no-force
-v, --verbose
-h, --help
EOF
}
declare -a FILES=()
declare OUTPUT=
declare -i FORCE=0 VERBOSE=0
function parse_opts () {
local opt=
while (( $# )); do
opt="$1"
shift
case "$opt" in
-o|--output)
OUTPUT="$1"
shift
;;
-f|--force)
FORCE=1
;;
-F|--no-force)
FORCE=0
;;
-v|--verbose)
(( VERBOSE+=1 ))
;;
-h|--help)
usage
exit 0
;;
--)
FILES+=("$@")
shift $#
;;
-)
FILES+=(-)
;;
-*)
usage >&2
echo >&2
echo >&2 "invalid option: ${opt}"
exit 1
;;
*)
FILES+=("$opt")
;;
esac
done
}
declare -a PREPARED_OPTS=()
function prepare_opts () {
local opt= char=
PREPARED_OPTS=()
while (( $# )); do
opt="$1"
shift
case "$opt" in
--)
PREPARED_OPTS+=(-- "$@")
shift $#
;;
--*)
# long option
if [[ $opt =~ ^(--[^=]+)=(.*)$ ]]; then
PREPARED_OPTS+=("${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}")
else
PREPARED_OPTS+=("$opt")
fi
;;
-)
PREPARED_OPTS+=(-)
;;
-*)
# short option
# https://stackoverflow.com/questions/10551981
while IFS= read -r -d '' -n 1 char; do
PREPARED_OPTS+=("-${char}")
done < <(printf "%s" "${opt#-}")
;;
*)
PREPARED_OPTS+=("$opt")
;;
esac
done
}
function main () {
echo "OUTPUT=${OUTPUT}"
echo "FORCE=${FORCE}"
echo "VERBOSE=${VERBOSE}"
echo "FILES="
local file=
for file in "${FILES[@]}"; do
echo " ${file}"
done
}
prepare_opts "$@"
parse_opts "${PREPARED_OPTS[@]}"
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment