Last active
April 16, 2024 18:19
-
-
Save james2doyle/387025893ff3d12fa414bd404ab835d4 to your computer and use it in GitHub Desktop.
An example of a bash script that has required arguments
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 | |
# e (errexit): Abort script at first error | |
# u: Treat unset variables as an error | |
# f: Disable filename expansion (globbing) upon seeing *, ?, etc.. | |
# pipefail: Causes a pipeline to return exit code for last command in pipe | |
set -euf -o pipefail | |
# run this if the script exits with a non-zero exit code | |
handle_error() { | |
echo "We got an error... so do some cleanup..." | |
# Additional error handling logic | |
exit 1 | |
} | |
# set the error handler function | |
trap handle_error ERR | |
if [ $OPTIND -eq 1 ]; then | |
echo "No options were passed" | |
exit 1 | |
fi | |
while getopts a:b:c: option | |
do | |
case "${option}" | |
in | |
a) A=${OPTARG};; | |
b) B=${OPTARG};; | |
c) C=${OPTARG};; | |
# there are options but no matches | |
*) echo "Usage: getops.sh -a A -b B -c C" >&2 | |
exit 1;; | |
esac | |
done | |
# we made it past the guards! | |
echo "A=$A B=$B C=$C" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment