Reputation: 10254
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?
Upvotes: 3
Views: 9010
Reputation: 88684
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.
Upvotes: 7
Reputation: 185274
#!/usr/bin/env bash
# Stop the script if any commands fail
set -euo pipefail
# Start a server
yarn serve &
SERVER_PID=$!
trap "kill $SERVER_PID" 0 1 2 3 15
# Run some cURL requests against the server
...
Note the use of trap
Upvotes: 6