为什么我的npm脚本没有打印变量的内容?

huangapple go评论49阅读模式
英文:

Why does my npm script not print the content of the variable?

问题

我想运行一个shell命令,检查其输出,并且如果输出不为空,将输出作为错误消息的一部分打印出来。
为了实现这个目的,我尝试使用命令替换,但出于某种原因,我无法打印变量的内容。
请考虑我的package.json中的npm run scripts如下所示:

"scripts": {
    "bar": "sh -c 'VAR=$(echo hello) env | grep VAR'",
    "baz": "sh -c 'VAR=$(echo hello) echo $VAR'",
},

命令替换的工作方式如npm run bar所示:

$ npm run bar

> project@0.1.0 bar
> sh -c 'VAR=$(echo hello) env | grep VAR'

VAR=hello
npm_lifecycle_script=sh -c 'VAR=$(echo hello) env | grep VAR';

hello已正确赋给变量VAR
不幸的是,我无法打印其内容,如npm run baz所示:

$ npm run baz  

> project@0.1.0 baz
> sh -c 'VAR=$(echo hello) echo $VAR'


$ echo $?
0

我的代码基于这个SO帖子。我在这里漏掉了什么?

英文:

I want to run a shell command, check its output and print the output as part of the error message if the output is not empty.
To achieve this, I'm trying to use command substitution but for some reason I cannot print the content of the variable.
Consider npm run scripts in my package.json as follows:

"scripts": {
    "bar": "sh -c 'VAR=$(echo hello) env | grep VAR'",
    "baz": "sh -c 'VAR=$(echo hello) echo $VAR'",
},

The command substitution works as shown by npm run bar:

$ npm run bar

> project@0.1.0 bar
> sh -c 'VAR=$(echo hello) env | grep VAR'

VAR=hello
npm_lifecycle_script=sh -c 'VAR=$(echo hello) env | grep VAR'

The value hello has been correctly assigned to the variable VAR.
Unfortunately, I cannot print its content as shown by npm run baz:

$ npm run baz  

> project@0.1.0 baz
> sh -c 'VAR=$(echo hello) echo $VAR'


$ echo $?
0

My code is based on this SO post. What am I missing here?

答案1

得分: 1

在变量定义和echo语句之间加上分号应该可以解决你的问题。

 VAR=$(echo hello); echo $VAR

 >>> hello
英文:

Placing a semicolon between the definition of the variable and the echo statement should solve your problem.

 VAR=$(echo hello); echo $VAR

 >>> hello

huangapple
  • 本文由 发表于 2023年7月27日 17:08:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定