CodexBloom - Programming Q&A Platform

Handling SIGTERM in a Bash Script when Running in Background

๐Ÿ‘€ Views: 4427 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-17
bash signal-handling nohup Bash

I've searched everywhere and can't find a clear answer. I'm maintaining legacy code that I'm trying to run a long-running Bash script in the background on my Ubuntu 20.04 server, but I'm having trouble with how it handles termination signals. I'm using the following script to start a long process: ```bash #!/bin/bash long_running_task() { while true; do echo "Running..." sleep 5 done } trap 'echo "Terminated"; exit' SIGTERM long_running_task & wait ``` When I run this script and then send a SIGTERM signal using `kill`, the script does not seem to handle the signal as expectedโ€”it terminates without executing the trap command. I expect it to print "Terminated" before exiting. When I test it by running the script directly in the terminal (not in the background), the trap works perfectly. I tried modifying the way the script is invoked, using `nohup` and different shell options, but I haven't had any success. Hereโ€™s how I start the script: ```bash nohup ./my_script.sh & ``` The scenario seems to be related to the process group or how `nohup` handles the SIGTERM signal. Does anyone have insights on why the trap isn't being executed, and how I can ensure that my script properly handles termination when running in the background? Any suggestions or workarounds would be greatly appreciated! Am I approaching this the right way? I'm on macOS using the latest version of Bash. Could someone point me to the right documentation?