bash: add message lib example

This commit is contained in:
Mathieu Maret 2022-02-25 17:32:06 +01:00
parent 3dbb62d303
commit 0cbd465e41
3 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,18 @@
#!/usr/bin/env bash
myfunct() {
local a=10
debug "my a variable is $a"
msg "value of 'a' squared: $(( a * a ))"
}
check_file() {
if [ ! -f "monfichier.txt" ]
then
display_error "File monfichier.txt not found"
fi
}
display_error() {
error "$*"
}

View File

@ -0,0 +1,55 @@
#!/usr/bin/env bash
DATE_FMT="+%s"
msg() {
local message="$*"
[ -z "$message" ] && return
if [ -t 1 ]
then
printf "%b\n" "$message"
else
log "$message"
fi
}
log() {
local message="${*-}"
[ -z "$message" ] && return
printf "%s %b\n" "$(date $DATE_FMT)" "$message"
}
debug() {
local message="$*"
[[ -z $DEBUG || $DEBUG -ne 1 ]] && return
[ -z "$message" ] && return
message="DEBUG [${BASH_SOURCE[1]}:${FUNCNAME[1]}]: $message"
if [ -t 2 ]
then
>&2 msg "\e[34m$message\e[0m"
else
>&2 log "$message"
fi
}
error() {
local message="$*"
[ -z "$message" ] && return
message="ERROR: $message"
if [[ -n $DEBUG && $DEBUG -eq 1 ]]
then
message="$message\n\tstack trace:\n"
for (( i=1; i<${#FUNCNAME[@]}; i++ ))
do
message="${message}\t source:${BASH_SOURCE[i]}"
message="${message} function:${FUNCNAME[$i]}"
message="${message} line:${BASH_LINENO[$i-1]}\n"
done
fi
if [ -t 2 ]
then
>&2 msg "\e[31m$message\e[0m"
else
>&2 log "$message"
fi
}

9
scripts/message_bash/test.sh Executable file
View File

@ -0,0 +1,9 @@
#!/usr/bin/env bash
source message.sh || { >&2 printf "Can't load message.sh"; exit 1; }
source include.sh || { >&2 printf "Can't load include.sh"; exit 1; }
myfunct
check_file
debug "We will display a message"
msg "Test Message"
error "This is a simple error message"
exit 0