英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论