It happens that tail
dies because of the CTRL+C but it is also sent (SINGINT) to the parent, bash
. Since by default bash dies when receive such signal, you have to replace the default behavior of bash
when receives it.
Use trap built-in command of bash(1)
to change this.
Following script tailf-ctrl.sh
is a demo and shows the answer:
#!/bin/bash
function finish {
echo "CTRL-C pressed!"
}
F=testfile
echo hello > $F
# set custom action
trap finish SIGINT # comment this to see the problem
tail -f $F
# reset default action
trap - SIGINT
echo "Hello after" > after
cat after
note that:
- SIGINT is the signal related to CTRL+C
- first trap install a custom action related to the SIGINT signal
- second trap reset default behavoir of the SIGINT signal
Output of the script is:
$ bash tailf-ctrl.sh
hello
^CCTRL-C pressed!
Hello after
that shows that the second file is written so the end of script is reached when tail
dies because of the CTRL-C
.
if you comment out the first trap command, you see your problem appears: bash immediately terminates and the output should be:
$ bash tailf-ctrl.sh
hello
^C
$
Worked as expected, thx. Wasn't familiar with
trap
, seems to be very useful – igor – 2018-02-08T07:02:56.930