I'm writing a script in Bash that looks something like this:
#!/usr/bin/env bash
# Stop the script if any commands fail
set -euo pipefail
# Start a server
yarn serve &
SERVER_PID=$!
# Run some cURL requests against the server
...
# Stop the server
kill $SERVER_PID
What I'd like to do is ensure kill $SERVER_PID is always called at the end of the script, even if one of the server commands fails. Is there a way to accomplish this in Bash?
Insert
trap "kill $SERVER_PID" ERR
in a new line after SERVER_PID=$!.
From help trap:
ERR means to execute ARG each time a command's failure would cause the shell to exit when the -e option is enabled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With