我有一个非常简单的 shell 脚本,test.sh
#!/usr/bin/env bash
exit 1
我从 package.json
中的 test
运行脚本调用此函数
"scripts": {
"test": "test.sh && echo \"unexpected output\""
},
运行npm test
我得到这个:
$ npm test
> testtest@1.0.0 test C:\Users\[path]\testtest
> test.sh && echo "unexpected output"
"unexpected output"
npm 似乎并不关心 test.sh 的非零退出代码。我没想到会看到“意外的输出”。
当 "test"
命令执行的其中一个步骤(本例中为 test.sh
)因错误退出时,如何停止执行该命令?
在我的 package.json 中:"test": "test.sh && echo $?",
这是输出:
$ npm test
> testtest@1.0.0 test C:\Users\[path]\testtest
> test.sh && echo $?
$?
这样:"test": "test.sh && echo\"$?\"",
我明白了:
$ npm test
> testtest@1.0.0 test C:\Users\[path]\testtest
> test.sh && echo "$?"
"$?"
作为健全性检查,我在 test.sh
退出后添加了一个回显。幸好它没有打印:)
#!/usr/bin/env bash
exit 1
echo "This should not print"
“这不应该打印”文本永远不会出现在我的控制台中。
实际上,在 exit 1
之前添加 echo
也不会在我的 GitBash 控制台上打印任何内容。相反,它会打印到 npm 启动的临时 cmd 窗口。所以我猜测退出状态在该 cmd session 中丢失了。
最佳答案
这对我有用:
"scripts": {
"test": "bash test.sh && echo \"unexpected output\""
},
使用附加的“bash”,脚本将在当前的 Git Bash 中运行。不打印“意外输出”。 如果我省略“bash”,则会打开一个新的 Bash 窗口,并且我还会得到“意外的输出”。
$ 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.
顺便说一句,如果您正在开发跨平台 Node.js 项目,最好避免使用 Bash/Cmd/Powershell 脚本。只需使用 Node.js 脚本即可,无需安装其他工具。
关于node.js - Windows 上 npm run 脚本中 shell 脚本的退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48387948/