【问题标题】:Exit status from shell scripts in npm run scripts on windows在 Windows 上运行 npm 脚本中的 shell 脚本的退出状态
【发布时间】:2018-07-01 11:02:23
【问题描述】:

我有一个非常简单的 shell 脚本,test.sh

#!/usr/bin/env bash

exit 1

我从testpackage.json 中的运行脚本调用它

"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 会话中丢失了。

【问题讨论】:

  • 您能否发布将 echo 消息替换为 echo $? 时发生的情况(只是为了确保退出代码正确到达 1)。 $? returns the exit code of the last run command.
  • @Squirrel 我得到字符串$? :(
  • 一个想法是尝试 set -e (as explained in this question),也许 .sh 脚本没有被节点正确停止?另外,为了确保您的线路以test.sh && echo $? 结尾,对吧?
  • @Squirrel 刚找到这个页面,遇到了同样的问题,很失望的发现解决办法一直私聊:(
  • @Katie 没有找到解决方案:(

标签: node.js windows bash npm


【解决方案1】:

这对我有用:

"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 脚本即可,不需要安装额外的工具。" -- 我对调用process.exit() 的.js 文件有同样的问题。你是如何让它工作的?
  • @Bbrk24 我没有这个问题(Win10,节点 12):"scripts": { "test0": "node index.js 0 && echo \"Expected output\"", "test1": "node index.js 1 && echo \"Unexpected output\"" },。 Index.js 包含:var code = parseInt(process.argv[2]); console.log('exit ' + code); process.exit(code);。当我运行npm run test0 时,我得到“exit 0 / Expected output”。当我运行npm run test1 时,我只得到“exit 1”,正如预期的那样。
猜你喜欢
  • 2017-05-18
  • 2013-09-09
  • 1970-01-01
  • 2013-01-05
  • 2013-03-01
  • 2017-12-11
  • 1970-01-01
  • 2013-12-19
  • 1970-01-01
相关资源
最近更新 更多