Last active
November 26, 2024 16:59
-
-
Save noslin005/5f60d31fb2f47597910cde80432df65e to your computer and use it in GitHub Desktop.
Sample bash script
This file contains hidden or 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 | |
################################################################################ | |
## File: script.sh | |
## Desc: Sample bash argument processing | |
## Author: Nilson Lopes <[email protected]> | |
################################################################################ | |
set -o nounset | |
PROGRAM_NAME=$(basename "$0") | |
LOGFILE="/tmp/$(date +%Y%m%d-%H%M).log" | |
VERSION="1.0" | |
SERIAL=0 | |
# Check for root. | |
if (($(id -u) != 0)); then | |
echo "This script must be run with root privileges." | |
exit 1 | |
fi | |
function usage() { | |
cat <<EOF | |
${PROGRAM_NAME} - Version ${VERSION} | |
Usage: ${PROGRAM_NAME} [OPTIONS] ... | |
-s, --serial System Serial Number. | |
-h, --help Display this help menu. | |
EOF | |
} | |
function parse_arguments() { | |
local -r SHORT_OPTIONS="hs:" | |
local -r LONG_OPTIONS="help,serial:" | |
if [ $# -eq 0 ]; then | |
usage | |
exit 1 | |
fi | |
# Parse arguments | |
if ! OPTIONS=$(getopt -o "$SHORT_OPTIONS" --long "$LONG_OPTIONS" -n "$PROGRAM_NAME" -- "$@"); then | |
usage | |
exit 1 | |
fi | |
eval set -- "$OPTIONS" | |
while true; do | |
case "$1" in | |
-s | --serial) | |
SERIAL="$2" | |
shift 2 | |
;; | |
-h | --help) | |
usage | |
exit 0 | |
;; | |
--) | |
shift | |
break | |
;; | |
*) | |
echo "Internal error!" | |
exit 1 | |
;; | |
esac | |
done | |
} | |
# command line parsing | |
parse_arguments "$@" | |
# start logging | |
exec \ | |
3>&1 \ | |
4>&2 \ | |
5>>"$LOGFILE" \ | |
> >(tee -a "$LOGFILE") \ | |
2> >(tee -a "$LOGFILE" >&2) | |
# add your logic here | |
echo "$SERIAL" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment