In a bash script, if a user sends a running script to the background with CTRL+Z, is it possible to do some work before the system takes the script to the background?
I know it’s possible to do work on EXIT signals (and others) for example, with trap
.
For example:
<code>#!/bin/bash
trap foo SIGINT SIGTERM SIGHUP SIGQUIT
trap bar SIGSTOP
foo() {
echo "Interrupted"
# do other cleanup, etc
}
bar() {
# do stuff first
echo "Sending to background..."
}
sleep 30
</code>
<code>#!/bin/bash
trap foo SIGINT SIGTERM SIGHUP SIGQUIT
trap bar SIGSTOP
foo() {
echo "Interrupted"
# do other cleanup, etc
}
bar() {
# do stuff first
echo "Sending to background..."
}
sleep 30
</code>
#!/bin/bash
trap foo SIGINT SIGTERM SIGHUP SIGQUIT
trap bar SIGSTOP
foo() {
echo "Interrupted"
# do other cleanup, etc
}
bar() {
# do stuff first
echo "Sending to background..."
}
sleep 30
But why doesn’t that work?
Desired:
<code>$ bash example.sh
^CInterrupted
$ bash example.sh
^Z
Sending to background...
[1]+ Stopped bash example.sh
</code>
<code>$ bash example.sh
^CInterrupted
$ bash example.sh
^Z
Sending to background...
[1]+ Stopped bash example.sh
</code>
$ bash example.sh
^CInterrupted
$ bash example.sh
^Z
Sending to background...
[1]+ Stopped bash example.sh
Actual output:
<code>$ bash example.sh
^CInterrupted
$ bash example.sh
^Z
[1]+ Stopped bash example.sh
</code>
<code>$ bash example.sh
^CInterrupted
$ bash example.sh
^Z
[1]+ Stopped bash example.sh
</code>
$ bash example.sh
^CInterrupted
$ bash example.sh
^Z
[1]+ Stopped bash example.sh