I have two shell scripts, one runs on a server and writes some files to a temporary directory. This directory is then sent as a tar archive to stdout. At the end (or when it gets interrupted), the temporary directory should be deleted. The server script (saved e.g. in '~/get_dumps.sh') looks like this:
#!/bin/sh
set -e
temp_dir=`mktemp -d`
cd $temp_dir
trap "rm -r $temp_dir; exit" HUP INT TERM PIPE
for db in db1 db2 db3
do
pg_dump $db postgres > $db.sql
done
tar cJf - .
rm -r $temp_dir
The server script is called from a client with this script:
#!/bin/sh
set -e
temp_dir=`mktemp -d`
trap "rm -r $temp_dir; exit" HUP INT TERM PIPE
mkdir /tmp/dumps
ssh server '~/get_dumps.sh' | tar xJf - -C $temp_dir
ls $temp_dir
rm -r $temp_dir
If I run the client script and press Ctrl-C, neither on the client nor on the server the temporary directories are removed. Why does trap here not work?
Edit: First I have forgotten to add set -e.
/bin/sh)? What point is the script at when you CTRL+C it? Have you tried running the script with debug output (set -x)?set -x. In the local test scripts, I had includedset -eand forgotten to add it to the example code above. Withset -xor withoutsetit works. It seams thatset -eis incompatible with trap.set -eis not incompatible withtrap. Where does the script(s) terminate if you useset -e?pg_dumportar. With or withoutset -e, the result is in both cases the same: The execution ofpg_dumportarstops immediately (and the script exits directly afterpg_dumportar). Withset -e(x),trapis not called, withset -x(or withoutset) it works as intended.set -e. Then you say it works withoutset -e. Confused.