To jump straight in:
while true; do
#--- MENU LOGIC HERE, stick response in $MENUEXIT
#----Deal with responses here
if [ $S1 == $MENUEXIT ];
then
tail -f /path-to-file
else
sleep 2
fi
done
I've tried to keep this as simple as possible, if you need more, let me know.
Basically, I am sticking a menu in a loop, so, if there is incorrect user input or a command finishes, it is meant to re-display the menu.
It worked fine, until I added the tail command.
If I choose the tail option from the menu, the tail command gets launched fine - but, if I hit Ctrl + C, I would like tail to terminate and the menu to be displayed, but it instead both terminates tail AND the script.
I have tried various things such as continues/traps and more, but, I have hit a brick wall and would like some help please?!
When you send a signal like
SIGINT
(CtrlC) orSIGSTOP
(CtrlZ) from a terminal, the signal is sent to the foreground process group. That is, the group comprising of the foreground job (your script), and any child processes it has in the foreground (thetail
command). This causes all these processes to exit (or do whatever it is they do by handling the signal). You can test the difference by sending a signal using thekill
command:In one terminal, execute this script (I'm calling it
test
in the following commands):In another, execute these commands:
The output of the commands would be something like this:
(The actual numbers and programs may vary, but the first init will always have pid 1.)
As you can see, the
yes
command wasn't killed, and got attached toinit
because its parent was killed. It's still merrily printingy
s on the first terminal. So kill it withpkill -f yes
. Now repeat the experiment, with one change. Instead ofpkill -f test
, do:Note the leading
-
. In Linux, for thekill
command,-25165
is the process group, whose leader has pid25165
. Thus, this command is the equivalent of sending an interrupt from the terminal.Of course, the exact behaviour depends on the configuration of the TTY, the login shell and so on. This is as far as my understanding goes. Further reading:
I suggest:
tail
to the backgroundAn example:
This can become very powerful, by using different functions for trapping, and each doing their own clean up work.