#!/bin/bash # this is still broken it seems! much better to plain 'exit on failure' with a 'wrapper script' solution FAIL_MAIL=sam LOG=/tmp/process_`date +%Y%m%d-%H%M%S`.log handle_failure() { mail -s "process failed" $FAIL_MAIL < $LOG && echo >&2 sent mail to $FAIL_MAIL trap '-' EXIT exit 1 } handle_error() { echo >&2 exit due to error handle_failure } process() { # do some stuff sleep 5 && echo 5 seconds & file_count=`ls $HOME | wc -l` [ $(($RANDOM % 2)) = 0 ] echo "You have $file_count files in $HOME" wait } TERM_subprocs() { echo trap '' TERM kill -TERM -$$ } handle_exit() { TERM_subprocs exit 0 } handle_signal() { echo >&2 exit due to signal TERM_subprocs handle_failure } #set -E -e -u -o pipefail trap handle_signal 1 4 5 6 7 8 9 10 11 12 13 14 15 16 24 25 26 27 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 # system-dependent #trap handle_exit EXIT process 2>&1 | tee $LOG if [ $? -ne 0 ]; then handle_error fi