Skip to content

Instantly share code, notes, and snippets.

@a-chen
Last active April 24, 2018 21:39
Show Gist options
  • Save a-chen/4f21a1c6fe27f81ebf2216f139ad2dcd to your computer and use it in GitHub Desktop.
Save a-chen/4f21a1c6fe27f81ebf2216f139ad2dcd to your computer and use it in GitHub Desktop.
Shell script template with long arguments
#!/usr/bin/env bash
set -o errexit
set -o pipefail
usage() {
echo "
${0##*/}
DESCRIPTION:
Script explanation
USAGE:
${0##*/} [OPTION] ... [OPTION]
-n | --longoption (required)
description
-? -h
display this help and exit
EXAMPLE:
${0##*/} -n"
}
# check for empty argument
if [[ -z "$1" ]] ; then
usage
exit 1
fi
# parse options
# short options after -o
# long options after --long
# add : after options that require a value and shift by 2
# e.g. -m | --memory ) MEMORY="$2"; shift 2 ;;
# for options that do not require a value, shift by 1
# e.g. -v | --verbose ) VERBOSE=true; shift ;;
# script name after -n
# $1 is option, $2 is the option argument
TEMP=`getopt -o vd:h --long longoption,longoption-with-argument:,help \
-n 'programname' -- "$@"`
if [[ $? != 0 ]] ; then echo "Terminating..." >&2 ; exit 1 ; fi
eval set -- "$TEMP"
while true; do
case "$1" in
-v | --longoption)
echo v and verbose; shift;;
-d | --longoption-with-argument)
echo arguement is $2; shift 2;;
-h | --help)
usage
exit 2
break;;
--)
shift; break;;
*)
break;;
esac
done
# stores working directory
working_directory=$(pwd)
# stores script directory
script_directory="$(cd $(dirname $0); pwd)"
# changes to script directory
cd "$script_directory"
# check required arguments
if [[ -z "$requirement" ]] || [[ -z "$requirement" ]]; then
usage
exit 6
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment