I have script that reads lines from a file, processes each line. I'd like to be able to do some "post-processing" in a way that even when the script didn't finish reading all lines because I pressed Ctrl+C it would still do the post processing. To achieve this I'm trying to do both of the following:
- redirect stdout to a file; Later do the post-processing from that file, however I'd like to see what's going on, so I'd like to redirect to "tee"
- trap Ctrl+C and do the post processing there
I managed to make either 1 or 2 work, but not both at the same time:
#!/bin/bash
# 2. Either this works
# trap ctrl-c and call ctrl_c()
trap ctrl_c INT
function ctrl_c() {
echo "** Trapped CTRL-C"
}
# 1. Or this works
LOGFILE=/tmp/${FILE}.tee
rm ${LOGFILE}
exec > >(tee ${LOGFILE}) 2>&1
function post_process() {
# use ${LOGFILE}
}
egrep "(${URL_PATH})" ${FILE} |
while read LINE ; do
#...
done
post_process
post_process
to thectrl_c
function and use thetee
redirection for thewhile
loop only?exec 3>&1 >output; ...; exec >&3
. But please read my answer -- you do not have to do that.