Home > Blockchain >  npm scripts: chaining commands with && works, but fails with ;
npm scripts: chaining commands with && works, but fails with ;

Time:07-19

Having a strange issue here with npm (on Windows, if it matters).

Chaining two commands with && works fine:

"test:integration": "firebase emulators:exec --non-interactive \"npm run test:integration:runner\" && kill-port 9000",

But if I substitute ; for && it fails to work:

"test:integration": "firebase emulators:exec --non-interactive \"npm run test:integration:runner\" ; kill-port 9000",

Instead of running the first command successfully, npm run test:integration just returns immediately if I use ;.

I want to run kill-port 9000 as cleanup after the first command, regardless of the exit status from the first command, which is why I switched to ;.

Any idea what's going on here? Is there an alternative way I can do this besides using ;?

(I did get it working by chanining && and || like (first_command && kill-port 9000) || kill-port 9000, but that seems hackish and I would like to understand why ; isn't working)

CodePudding user response:

The shell that npm utilizes to run npm scripts on Windows is cmd by default. However on *nix (Linux, macOS, ...) it utilizes sh as the default shell to run npm scripts.

As you’re using Windows, (essentially using cmd when running npm scripts), then consider substituting the semicolon (;) with the AND operator, i.e. a single ampersand (&).

The AND operator in cmd (&) has the same logic as the semicolon (;) in sh on *nix - which is essentially execute command 2 regardless of whether command 1 fails or succeeds.

Notes:

  1. Be mindful that the AND operator (&) has a different meaning/logic in sh on *nix.
  2. FYI, I answered a similar question here.
  • Related