bash: add message lib example
This commit is contained in:
parent
3dbb62d303
commit
0cbd465e41
18
scripts/message_bash/include.sh
Normal file
18
scripts/message_bash/include.sh
Normal 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 "$*"
|
||||
}
|
55
scripts/message_bash/message.sh
Normal file
55
scripts/message_bash/message.sh
Normal 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
9
scripts/message_bash/test.sh
Executable 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
|
Loading…
Reference in New Issue
Block a user