Skip to content

Instantly share code, notes, and snippets.

@dsummersl
Created November 29, 2018 16:30
Show Gist options
  • Save dsummersl/218c7587c25194aaef420b8bd3b3c526 to your computer and use it in GitHub Desktop.
Save dsummersl/218c7587c25194aaef420b8bd3b3c526 to your computer and use it in GitHub Desktop.
Shell script snippets
#!/bin/bash
# nounset: undefined variable outputs error message, and forces an exit
set -u
# errexit: abort script at first error
set -e
# print command to stdout before executing it:
set -x
getopt --test > /dev/null
if [[ $? -ne 4 ]]; then
echo "I’m sorry, getopt() will fail in this environment."
exit 1
fi
OPTIONS=o:v
LONGOPTIONS=output:,verbose
# -temporarily store output to be able to check for errors
# -e.g. use “--options” parameter by name to activate quoting/enhanced mode
# -pass arguments only via -- "$@" to separate them correctly
PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTIONS --name "$0" -- "$@")
if [[ $? -ne 0 ]]; then
# e.g. $? == 1
# then getopt has complained about wrong arguments to stdout
exit 2
fi
# read getopt’s output this way to handle the quoting right:
eval set -- "$PARSED"
while true; do
case "$1" in
-v|--verbose)
verbose=y
shift
;;
-o|--output)
outFile="$2"
shift 2
;;
--)
# split until we see --
shift
break
;;
*)
echo "Programming error"
exit 3
;;
esac
done
# handle non-option arguments
if [[ $# -ne 1 ]]; then
echo "$0: A single input file is required."
exit 4
fi
echo "verbose: $verbose, force: $f, debug: $d, in: $1, out: $outFile"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment