Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Ensure a command always runs when using set -euo pipefail

Tags:

bash

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?

like image 406
LandonSchropp Avatar asked Dec 11 '25 08:12

LandonSchropp


1 Answers

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.

like image 174
Cyrus Avatar answered Dec 14 '25 05:12

Cyrus