Skip to content

Instantly share code, notes, and snippets.

@jRimbault jRimbault/template.sh
Last active May 10, 2018

Embed
What would you like to do?
Bash script template
#!/usr/bin/env bash
#/ Script Name: template.sh
#/ Author: jRimbault
# Date: 2017-04-06
#/
#/ Description:
#/ This is a template file meant to be used for all my future
#/ bash scripting.
#/
#/ Error Log:
#/ Any errors or output associated with
#/ the script can be found in /tmp/template.sh.log
#/
#/ Run Information:
#/ I shoud write here informations about how and why to run
#/ this script.
#/
#/ Usage: template.sh <template>
#/
#/ Options:
#/ --help, -h display this help
usage()
{
grep "^#/" "$0" | cut -c4-
exit 0
}
# define paramters here
args()
{
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help)
usage
;;
esac
shift
done
}
set -euo pipefail
# read-only globals
readonly NOCOL="\\033[0m" # No color
readonly BLACK="\\033[0;30m" # Black
readonly WHITE="\\033[1;37m" # White
readonly LOG_FILE="/tmp/$(basename "$0").log" # temp log file
# colored output
__colored() { echo -e "$*$NOCOL"; }
_grey() { __colored "\\033[1;30m$*"; }
_light_grey() { __colored "\\033[0;37m$*"; }
_red() { __colored "\\033[0;31m$*"; }
_light_red() { __colored "\\033[1;31m$*"; }
_green() { __colored "\\033[0;32m$*"; }
_light_green() { __colored "\\033[1;32m$*"; }
_orange() { __colored "\\033[0;33m$*"; }
_yellow() { __colored "\\033[1;33m$*"; }
_blue() { __colored "\\033[0;34m$*"; }
_light_blue() { __colored "\\033[1;34m$*"; }
_purple() { __colored "\\033[0;35m$*"; }
_light_purple() { __colored "\\033[1;35m$*"; }
_cyan() { __colored "\\033[0;36m$*"; }
_light_cyan() { __colored "\\033[1;36m$*"; }
# log output
_cleanlog() { sed 's/\x1b\[[0-9;]*m//g' >> "$LOG_FILE"; }
_logger()
{
echo "$(_date) $*"
echo "$(_date) $*" | _cleanlog
}
_date() { date +"%Y-%m-%d %H:%M:%S"; }
_info() { _logger "[INFO] $*"; }
_warning() { _logger "[WARNING] $*"; }
_error() { _logger "[ERROR] $*"; }
_fatal() { _logger "[FATAL] $*"; exit 1 ; }
# use instead of echo for user output (not for writing to a file)
println() { _logger "$*"; }
# cleanup triggered on bad exit code
cleanup()
{
_light_red "$(_fatal "$@")"
}
# main
main()
{
_info "A few informations"
_warning "Eww, better be careful"
_error "Ewrk! An error!"
println "$(_cyan "$@")"
}
# do not execute script if it is sourced by another
if [[ "${BASH_SOURCE[0]}" = "$0" ]]; then
trap cleanup SIGHUP SIGINT SIGTERM
# for demo purposes, require at least 1 one arg
[[ $# -lt 1 ]] && usage
args "$@"
main "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.