O script abaixo definirá a função recordfailure
que deve ser anexada aos comandos, conforme mostrado no exemplo após a definição da função. Se o comando retornar diferente de zero, o fluxo de erro padrão será registrado. Finalmente, no final, o log de erros é verificado e [OK]
ou [FAIL]
é impresso de acordo.
#!/bin/bash
# Redirect file descriptor #3 to standard output (used in recordfailure)
exec 3>&1
# create an array for holding failures
declare -a failures
# recordfailure command arg1 arg2 ... argN
recordfailure() {
local error retval
# Run the command and store error messages (output to the standard error
# stream in $error, but send regular output to file descriptor 3 which
# redirects to standard output
error="$("$@" 2>&1 >&3)"
retval=$?
# if the command failed (returned a non-zero exit code)
if [ $retval -gt 0 ]; then
if [ -z "$error" ]; then
# create an error message if there was none
error="Command failed with exit code $retval"
fi
# uncomment if you want the command in the error message
#error="Command $* failed: $error"
# append the error to $failures, ${#failures[@]} is the length of
# the array and since array start at index 0, a new item is created
failures[${#failures[@]}]="$error"
# uncomment if you want to show the error immediately
#echo "$error"
fi
}
recordfailure iptables -A FORWARD ...
recordfailure iptables -A FORWARD ...
# if the length of the failures array equals 0 (no items) everything is OK
if [ ${#failures[@]} -eq 0 ]; then
echo "[OK]"
else
echo "[FAIL]"
# list every error
for failure in "${failures[@]}"; do
# optionally color it, format it or whatever you want to do with it
echo "error: $failure"
done
fi
Se você não deseja mostrar a saída padrão, remova exec 3>&1
e substitua >&3
por >/dev/null
.