简体   繁体   中英

Exit status from shell scripts in npm run scripts on windows

I have a very simple shell script, test.sh

#!/usr/bin/env bash

exit 1

I'm calling this from my test run script in package.json

"scripts": {
  "test": "test.sh && echo \"unexpected output\""
},

Running npm test I get this:

$ npm test

> testtest@1.0.0 test C:\Users\[path]\testtest
> test.sh && echo "unexpected output"

"unexpected output"

It seems as if npm doesn't care about the non-zero exit code of test.sh. I was not expecting to see "unexpected output".

How do I make the execution of the "test" command stop when one of the steps it performs ( test.sh in this case) exits with an error?

With this in my package.json: "test": "test.sh && echo $?",
This is the output:

$ npm test

> testtest@1.0.0 test C:\Users\[path]\testtest
> test.sh && echo $?

$?

With this: "test": "test.sh && echo \\"$?\\"",
I get this:

$ npm test

> testtest@1.0.0 test C:\Users\[path]\testtest
> test.sh && echo "$?"

"$?"

As a sanity-check I added an echo after the exit in test.sh . Thankfully it doesn't print :)

#!/usr/bin/env bash

exit 1

echo "This should not print"

The "This should not print" text never shows up in my console.

Actually, adding an echo before exit 1 also doesn't print anything to my GitBash console. Instead it prints to a temporary cmd window that npm launches. So I'm guessing the exit status is lost inside that cmd session.

This worked for me:

"scripts": {
  "test": "bash test.sh && echo \"unexpected output\""
},

With the additional "bash", the script runs in the current Git Bash. The "unexpected output" is not printed. If I omit the "bash", a new Bash window is opened, and I also get the "unexpected output".

$ npm test

> npm2@1.0.0 test D:\Martin\dev\npm-test\npm2
> bash test.sh && echo "unexpected output"

Hi from script! Next: exit 1
npm ERR! Test failed.  See above for more details.

As a side note, if you're developing a cross-platform Node.js project, it might be better to avoid Bash/Cmd/Powershell scripts. Just use Node.js scripts instead, and you don't need additional tools to be installed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM