How to Kill Background Child Process in Bash

Tags: July 13, 2020 12:52 PM
0 comments

Terminate Background Child Process in Bash

In Bash by child process that sent into background is still alive when main program is terminated. Take a look an example below.

#!/bin/bash

# Run a Python web server
python -m http.server src/ &

# Run SASS watcher and compiler...
sass --watch src/scss:src/css &

wait
When we run script above and terminate using CTRL+C Python and SASS are still running.

Solution to terminate Background Child Process in Bash

The solution to above problem is using shell built-in trap command.

#!/bin/bash

# Kill all child process (Python and SASS) when exit
trap "kill 0" EXIT

# Run a Python web server
python -m http.server src/ &

# Run SASS watcher and compiler...
sass --watch src/scss:src/css &

wait

Now when the script is exited all the child process even which has been sent as background process will also terminated.

References

Share on Facebook Twitter