Skip to content

Instantly share code, notes, and snippets.

@tskrynnyk
Forked from PhilipSchmid/bash-template.sh
Created September 20, 2020 13:45
Show Gist options
  • Save tskrynnyk/ab786dda534acdf02ef2527bcb368633 to your computer and use it in GitHub Desktop.
Save tskrynnyk/ab786dda534acdf02ef2527bcb368633 to your computer and use it in GitHub Desktop.
Bash script template (incl. logging functions)
#!/bin/bash
#################################
# Constants / global variables
#################################
LOGFILE='example.log'
LOGLEVEL='INFO'
#################################
# Functions
#################################
# Logging functions
function log_output {
echo `date "+%Y/%m/%d %H:%M:%S"`" $1"
echo `date "+%Y/%m/%d %H:%M:%S"`" $1" >> $LOGFILE
}
function log_debug {
if [[ "$LOGLEVEL" =~ ^(DEBUG)$ ]]; then
log_output "DEBUG $1"
fi
}
function log_info {
if [[ "$LOGLEVEL" =~ ^(DEBUG|INFO)$ ]]; then
log_output "INFO $1"
fi
}
function log_warn {
if [[ "$LOGLEVEL" =~ ^(DEBUG|INFO|WARN)$ ]]; then
log_output "WARN $1"
fi
}
function log_error {
if [[ "$LOGLEVEL" =~ ^(DEBUG|INFO|WARN|ERROR)$ ]]; then
log_output "ERROR $1"
fi
}
# Some other helper functions
# ...
# Help output
function usage {
echo
echo "This is a Bash script template"
echo "Usage: ./example.sh -l <logfile> -L <loglevel>"
echo "Example: ./example.sh -l example.log -L INFO"
echo
}
#################################
# Main
#################################
# Get input parameters
while [[ "$1" != "" ]]; do
case $1 in
-l | --logfile ) shift
LOGFILE=$1
;;
-L | --loglevel ) shift
LOGLEVEL=$1
;;
-h | --help ) usage
exit
;;
* ) usage
exit 1
esac
shift
done
# Check input parameters and other required conditions
# Check if "docker" is installed
command -v docker >/dev/null 2>&1 || \
(log_error "Docker is required. Check if it's installed and available in the PATH." \
&& exit 1)
# Check if a param is set to a valid value
if [[ ! "$LOGLEVEL" =~ ^(DEBUG|INFO|WARN|ERROR)$ ]]; then
log_error "Logging level needs to be DEBUG, INFO, WARN or ERROR."
exit 1
fi
# Bash script logic starts here...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment