jeudi 28 juin 2018

How do I always run a "clean up" command in bash propagating the previous error code?

I'm setting up tests for a Node.js project. The tests include interacting with static content (images) that is supposed to be served from a local http-server.

When the tests have completed - either successfully or failing - I want to end the server process and exit with a correct code. What I came up with in my npm scripts is the following:

"server": "http-server testdata -p 9876 -s",
"testcmd": "...",
"test": "npm run server & npm run testcmd && kill $(lsof -t -i:9876) || (kill $(lsof -t -i:9876) && exit 1)",

which "works", but has two problems:

  • it repeats code as I do not know how to run things in any case instead of defining || and && cases
  • any non-zero exit code of testcmd will always be transformed into an 1 exit code - ideally I would like to propagate the exact exit code

I tried reading up on this and found people talking about traps, but could not get it to work.

What would be a good way to simplify this control flow scenario?

Aucun commentaire:

Enregistrer un commentaire