-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultimate-bash-api.sh
108 lines (91 loc) · 2.43 KB
/
ultimate-bash-api.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/bin/bash
# Name: Ultimate BASH API
# Version: 2017-08-27
# Description: Add nice pre-made functions to your bash scripts
# Developer: Robin Labadie
# Websites: lrob.fr | haisoft.fr | terageek.org
## Misc vars
function_nicename="Ultimate-Bash-API" # Name of the script
function_selfname="$(basename $(readlink -f "${BASH_SOURCE[0]}"))" # Name of this script file
function_rootdir="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))"
##############
## SETTINGS ##
##############
# Sleep
sleeptime="0" # Sleeptime settings
# Mailing
mail_notifications="off"
mailto_address="root@localhost" # Recipient mail alert address
# Logging
logdir="${function_rootdir}/log/" # Directory in which to save logs
if [ -n "${selfname}" ]; then
log="${logdir}/${selfname}.log"
else
log="${logdir}/${function_nicename}.log"
fi
############
## SCRIPT ##
############
currlog=""
# TIME
SECONDS=0
fn_logging(){
if [ -n "${logdir}" ]&&[ ! -d "${logdir}" ]; then
mkdir -pv "${logdir}"
fi
# Create logfile
if [ -n "${log}" ]&&[ ! -f "${log}" ]; then
touch "${log}"
fi
}
# Give a form to echo messages
fn_echo_form(){
echoform="$(date +%Y-%m-%d_%H:%M:%S) - ${selfname} - ${currmessage}"
}
# Simple echo with date and selfname
# Usage fn_echo "Your Message"
fn_echo(){
currmessage="$1"
fn_echo_form
echo -e "${echoform}"
}
# Simple log with date
# Usage fn_log "Your Message"
fn_log(){
currmessage="$1"
fn_echo_form
echo -e "${echoform}" >> "${log}"
currlog="${currlog}${echoform}\n"
}
# Echo with date and output to log at the same time
# Usage fn_logecho "Your Message"
fn_logecho(){
currmessage="$1"
fn_echo_form
echo -e "${echoform}"
echo -e "${echoform}" >> "${log}"
currlog="${currlog}${echoform}\n"
}
# Send mail notification
# Define mailsubject to your mail subject
# Define mailcontent to your mail body message
fn_mail(){
if [ "${mailalert}" == "on" ]; then
fn_logecho "[INFO] Sending mail alert to: ${mailto_address}"
echo -e "${mailcontent}" | mail -s "$(hostname -s) - ${mailsubject}" ${mailto_address}
fi
}
# Send mail containing all current log
fn_mail_currlog(){
if [ "${mail_notifications}" == "on" ]; then
fn_logecho "[INFO] Sending mail alert to: ${mailto_address}"
echo -e "${currlog}" | mail -s "$(hostname -s)" ${mailto_address}
fi
}
# Displays the duration since you executed this script
fn_duration(){
duration=$SECONDS
echo "[INFO] $(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed."
}
# Create log files
fn_logging