Skip to content

Instantly share code, notes, and snippets.

@TheLazyHatGuy
Created November 28, 2022 14:47
Show Gist options
  • Save TheLazyHatGuy/fb2f0f9dab64501ad8ab1d7f8d5fe136 to your computer and use it in GitHub Desktop.
Save TheLazyHatGuy/fb2f0f9dab64501ad8ab1d7f8d5fe136 to your computer and use it in GitHub Desktop.
Some Bash Utilities
# Set verbose level for .log function
# [0]="emerg"
# [1]="alert"
# [2]="crit"
# [3]="err"
# [4]="warning"
# [5]="notice"
# [6]="info"
# [7]="debug"
__VERBOSE=7
declare -A LOG_LEVELS
# https://en.wikipedia.org/wiki/Syslog#Severity_level
LOG_LEVELS=([0]="emerg" [1]="alert" [2]="crit" [3]="err" [4]="warning" [5]="notice" [6]="info" [7]="debug")
#.log <LEVEL> <STRING_TO_ECHO>
function .log () {
local LEVEL=${1}
shift
if [ ${__VERBOSE} -ge "${LEVEL}" ]; then
printf "[%s] %b\n" "${LOG_LEVELS[$LEVEL]}" "$@"
fi
}
function check-for-sudo() {
# Check if sudo/root permissions are available
if [[ "$EUID" = 0 ]]; then
.log 7 "(1) already root"
else
.log 6 "The script requires sudo/root access"
sudo -k # make sure to ask for password on next sudo
if sudo true; then
.log 7 "(2) correct password"
else
.log 7 "(3) wrong password"
.log 3 "Failed to gain sudo access. Exiting..."
exit ${FAILURE}
fi
fi
printf "\n\n"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment