04 July 2021

When I wrote complex bash that contains long operations could be necessary to manage a gracefully exit.

In unix/linux there is a command for this purpose: trap.

Note: There is special signals that cannot be caught or ignored, see wikipedia for more information.

Ignoring (do nothing) when received a specific signal

$ trap '' SIGTERM

Do something when received a specific signal

$ trap 'rm -f /tmp/mytmpfile$$; exit' SIGINT

Full Example

Bash script and save in /tmp/example_trap.sh:

#!/bin/bash

trap '' SIGTERM
trap 'echo "Received SIGINT, exit gracefully"; exit' SIGINT

echo "Start long operation"
sleep 120
echo "End long operation"

Then give them execution permission (like chmod +x) for /tmp/example_trap.sh.

docker run -it --mount 'type=bind,source=/tmp/,target=/tmp/' -w /tmp ubuntu /bin/bash

From inside the container:

# ./example_trap.sh &
[1] 27
Start long operation

Nothing happend for SIGTERM, as expected

# kill -SIGTERM 27
# 

The program exit gracefully with SIGINT

# kill -SIGINT 27 
Received SIGINT, exit gracefully
[1]+  Done  ./example_trap.sh

References