3 # mail-wrapper -- Report results of a command by email
4 # Copyright (c)2017,2018,2023 Alexander Barton (alex@barton.de)
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
14 # Include "ax-common.sh":
16 for dir in "$HOME/lib" "$HOME/.ax" /usr/local /opt/ax /usr; do
17 [ -z "$ax_common_sourced" ] || break
18 ax_common="${dir}/lib/ax/ax-common.sh"
19 # shellcheck source=/usr/local/lib/ax/ax-common.sh
20 [ -r "$ax_common" ] && . "$ax_common"
22 if [ -z "$ax_common_sourced" ]; then
23 echo "Error ($NAME): \"ax-common.sh\" not found, aborting!" >&2
24 echo "Please install 'ax-unix', \"Alex' UNIX Tools & Scripts\", and try again."
27 unset dir ax_common ax_common_sourced
33 echo " $NAME [--help|--usage]"
34 echo " $NAME {parameters} [<command> [<arg> [<…>]]]"
36 echo " -C Use the \"C\" locale, no localized (error) messages."
37 echo " --dontfail|-n Don't return the error code of the command called."
38 echo " --errors|-e Generate email on errors only."
39 echo " --from|-f Email address of the sender of the email."
40 echo " --stderr-is-warning|-W Exit code indicates error; stderr is only warning."
41 echo " --subject|-s <subject> Subject for the email."
42 echo " --to|-t <address> Email address to send the email to."
44 echo "When no <command> is given, $NAME reads from standard input. The default for"
45 echo "<from> and <to> for the current user is \"$to\"."
52 ax_error -l "Syntax error!"
57 if [[ -z "$proc_fd_works" ]]; then
58 ax_debug "Cleaning temporary files ..."
59 [[ -n "$buffer_file" ]] && rm -f "$buffer_file"
60 [[ -n "$error_file" ]] && rm -f "$error_file"
72 # Initialize internal state.
76 host=$(hostname -f 2>/dev/null || hostname)
80 # Some defaults (can be adjusted by command line parameters).
83 unset stderr_is_warning
85 from="${LOGNAME:-root} <${LOGNAME:-root}@$host>"
88 # Parse the command line ...
89 while [[ $# -gt 0 ]]; do
106 [[ $# -gt 0 ]] || syntax_error
114 [[ $# -gt 0 ]] || syntax_error
117 "--stderr-is-warning"|"-W")
121 # Ignore this switch for compatibility with an other
122 # "mail-wrapper" script. This is the default anyway!
126 [[ $# -gt 0 ]] || syntax_error
133 # Command to execute follows in command line.
140 # Initialize the "buffer file" on file handle #3. This file will store all
141 # output, stdout and stderr combined. The file is immediately unlinked so that
142 # we can't leak stale files. Afterwards this script accesses the "buffer file"
143 # by its file descriptor only.
144 buffer_file=$(mktemp) \
145 || ax_abort -l "Failed to create buffer file: \"$buffer_file\"!"
146 ax_debug "buffer_file=\"$buffer_file\""
147 exec 3>"$buffer_file" \
148 || ax_abort -l "Failed to redirect FD #3 to buffer file!"
149 if [[ -n "$proc_fd_works" ]]; then
151 || ax_error -l "Failed to delete buffer file: \"$buffer_file\"!"
152 buffer_file="/dev/fd/3"
155 if [[ $# -gt 0 ]]; then
156 # Execute command and save output in buffer file.
157 # Use a sub-shell to not pollute our name space!
158 error_file=$(mktemp) \
159 || ax_abort -l "Failed to create error buffer file: \"$error_file\"!"
160 ax_debug "error_file=\"$error_file\""
161 exec 4>"$error_file" \
162 || ax_abort -l "Failed to redirect FD #4 to error file!"
163 if [[ -n "$proc_fd_works" ]]; then
165 || ax_error -l "Failed to delete error buffer file: \"$error_file\"!"
166 error_file="/dev/fd/4"
171 ax_debug "Running command \"$*\" ..."
173 "$@" 2>&1 1>&3 | tee "$error_file" >&3
174 echo "${PIPESTATUS[0]}"
177 # Read from stdin and save it to the buffer file.
178 error_file="/dev/null"
181 ax_debug "Reading from stdin ..."
182 while read -r line; do
184 || ax_abort -l "Failed to write to buffer file!"
189 ax_debug "exit_code=$exit_code"
191 declare -i count_all count_err
192 count_all=$(wc -l <"$buffer_file" || ax_abort -l "Failed to count buffer file!")
193 count_err=$(wc -l <"$error_file" || ax_abort -l "Failed to count error file!")
195 # Error or no error -- that's the question! An error is assumed when either the
196 # exit code of the command was non-zero or there was output to stderr.
197 # But when stderr_is_warning is set, messages on stderr result on a warning only!
198 if [[ $exit_code -ne 0 ]]; then
200 elif [[ $count_err -gt 0 ]]; then
201 [[ -n $stderr_is_warning ]] && error_level=1 || error_level=2
206 # Construct email subject ...
207 [[ -z "$subject" ]] && subject="$host: $job report"
208 if [[ "$error_level" -eq 0 ]]; then
209 subject="$subject - success"
210 elif [[ "$error_level" -eq 1 ]]; then
211 subject="$subject - WARNING!"
213 subject="$subject - ERROR!"
216 ax_debug "from=\"$from\""
217 ax_debug "to=\"$to\""
218 ax_debug "subject=$subject"
220 if [[ -n "$DEBUG" ]]; then
221 echo "--- stdout+stderr ---"
223 echo "--- stderr ---"
228 ax_debug "count_all=$count_all"
229 ax_debug "count_err=$count_err"
230 ax_debug "error_level=$error_level"
232 # No errors detected (exit code & stderr), and email should be sent on errors
233 # only: so exit early!
234 [[ "$error_level" -lt 2 && -n "$do_errors_only" ]] && exit $exit_code
236 # No error detected and no output at all: skip email, exit early:
237 [[ "$error_level" -eq 0 && $count_all -eq 0 ]] && exit $exit_code
239 # Build the report mail.
240 # Make sure to ignore all mail(1) configuration files, system wide /etc/mailrc
241 # (by using the "-n" option) as well as ~/.mailrc (by setting the MAILRC
242 # environment variable).
243 export MAILRC=/dev/null
247 echo " - Host: $host"
248 echo " - User: $(id -un)"
249 echo " - Exit code: $exit_code"
251 if [[ $# -gt 0 ]]; then
252 # A command name is known (not stdin), show it!
257 if [[ $count_err -gt 0 ]]; then
258 # Prefix mail with all error messages.
259 echo "Error summary:"
260 echo "-----------------------------------------------------------------------------"
262 || ax_abort -l "Failed to dump error file!"
263 echo "-----------------------------------------------------------------------------"
266 if [[ $count_all -ne $count_err ]]; then
267 # Show full output when different to "error output" only.
269 || ax_abort -l "Failed to dump buffer file!"
271 ) | mail -n -a "From: $from" -s "$subject" "$to" \
272 || ax_abort -l "Failed to send email to \"$to\"!"
274 [[ -n "$dont_fail" ]] && exit 0 || exit $exit_code