Difference between revisions of "Linux shell/Functions"
Jump to navigation
Jump to search
(Created page with "A bunch of useful functions: <source lang=bash> cat > common_functions.sh <<EOF #!/usr/bin/env bash ########################################################################################## # log: trace message to stdout # Globals: # None # Arguments: # - $1: msg to render, if empty log does nothing # - $2: level tag, defaults to INFO # Returns: # outputs to stdout ########################################################################################## funct...") |
(No difference)
|
Latest revision as of 22:59, 24 August 2022
A bunch of useful functions:
cat > common_functions.sh <<EOF
#!/usr/bin/env bash
##########################################################################################
# log: trace message to stdout
# Globals:
# None
# Arguments:
# - $1: msg to render, if empty log does nothing
# - $2: level tag, defaults to INFO
# Returns:
# outputs to stdout
##########################################################################################
function log() {
msg=$1
if [[ -n ${msg} ]];then
level=${2:-"INFO"}
echo "$(date +"%Y-%m-%dT%T.%3N") - $level - $msg" &>/dev/stderr
fi
}
##########################################################################################
# current_datetime: returns string with date time formated as ddMMyyyy-HmS
# Globals:
# None
# Arguments:
# None
# Returns:
# None
##########################################################################################
function current_datetime() {
echo $(date +"%Y%m%d-%H%M%S")
}
##########################################################################################
# die: function exit with error message
#
# Arguments:
# $1 - exit code
# $2.... - message
# Returns:
# exit and exit code selected
##########################################################################################
function die() {
retcode=$1; shift
echo $@
exit $retcode
}
##########################################################################################
# checkEnvOrDie: check for the existence of a variable and if not found exits session
#
# Arguments:
# $1 - name of the variable, i.e. checkEnvOrDie HOME
# Returns:
# nothing, or exit with code 400 if fails
##########################################################################################
function checkEnvOrDie() {
env | grep $1 > /dev/null
if [[ $? -ne 0 ]]; then
die 400 "Env variable $1 must be set!";
fi
}
EOF