Last active
April 24, 2018 22:13
-
-
Save a-chen/b0752a7c126e9a5d0bd0c2da6f4a3086 to your computer and use it in GitHub Desktop.
shell-script-template-optargs.sh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -o errexit | |
set -o pipefail | |
usage() { | |
echo " | |
${0##*/} | |
DESCRIPTION: | |
Script explanation | |
USAGE: | |
${0##*/} [OPTION] ... [OPTION] | |
-n (required) | |
description | |
-? -h | |
display this help and exit | |
EXAMPLE: | |
${0##*/} -n" | |
} | |
# check for empty argument | |
if [ -z "$1" ] ; then | |
usage | |
exit 1 | |
fi | |
# check for options | |
while getopts "n:h-:" opt; do | |
case ${opt} in | |
n) | |
variable="$OPTARG" | |
;; | |
h) | |
usage | |
exit 2 | |
;; | |
\?) # invalid option | |
echo Invalid option: -"$OPTARG" | |
usage | |
exit 3 | |
;; | |
:) # missing option | |
echo Missing option argument for -"$OPTARG" | |
usage | |
exit 4 | |
;; | |
*) # unimplemented option | |
usage | |
exit 5 | |
;; | |
esac | |
done | |
# clear all options and reset the command line | |
shift $(( OPTIND -1 )) | |
# 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