Skip to content

Instantly share code, notes, and snippets.

@ssledz
Created April 15, 2021 10:09
Show Gist options
  • Save ssledz/1e56bfef257e70df1c95ad7bc7f51f62 to your computer and use it in GitHub Desktop.
Save ssledz/1e56bfef257e70df1c95ad7bc7f51f62 to your computer and use it in GitHub Desktop.

Revisions

  1. ssledz created this gist Apr 15, 2021.
    84 changes: 84 additions & 0 deletions getopts-template.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    #!/bin/bash

    DBG=0

    dbg() {
    [[ $DBG == 1 ]] && (1>&2 echo "[DEBUG] : "$1)
    }

    info() {
    echo "[INFO] : $1"
    }

    warn() {
    echo "[WARN] : $1"
    }

    err() {
    (1>&2 echo "[ERROR] : $1")
    }

    show_help() {
    cat << EOF
    Usage: ${0##*/} -p port [-d] [-h] arg1 arg2 ...argN
    Application description.
    -p port Port.
    -d Dry run.
    -h Print this help.
    EOF
    }


    dry_run=0
    port=

    while getopts ":p:dh" opt; do

    case $opt in
    p)
    port=$OPTARG
    ;;
    d)
    dry_run=1
    ;;
    h)
    show_help
    exit 0
    ;;
    \?)
    echo >&2
    echo " Invalid option: -$OPTARG" >&2
    show_help
    exit 1
    ;;
    :)
    echo >&2
    echo " Option -$OPTARG requires an argument" >&2
    show_help
    exit 2
    ;;
    *)
    show_help
    exit 3
    ;;
    esac

    done

    shift $((OPTIND-1)) # Shift off the options and optional --

    required=(port)

    for req in ${required[@]}; do
    [[ -z ${!req} ]] && echo && echo " Please specify $req" && show_help && exit 1
    done

    echo "Args: $*"

    [[ $dry_run -eq 1 ]] && info "Dry run"

    [[ $dry_run -eq 0 ]] && echo "Do something with port : $port"