如何在NPM脚本中使用Windows控制台“设置"变量?

问题描述:

这可以在Windows控制台中正常工作:

This works in Windows console as expected:

set A="qwerty" && echo %A%

输出:"qwerty"

但是当我尝试在NPM脚本中运行相同的命令时:

But when I try to run the same commands in NPM scipts:

package.json:

"scripts": {
  "qwerty": "set A=\"qwerty\" && echo %A%"
}

> npm run qwerty

输出为:%A%

我是在做错什么还是在NPM运行时不应该那样做?

Am I doing something wrong or it just shouldn't work that way when run by NPM?

您的示例set A="qwerty" && echo %A%不正确. cmd提示符/批处理文件中的变量每行/命令扩展一次:

Your example set A="qwerty" && echo %A% isn't correct. Variables in the cmd prompt / a batch file are expanded once per line / command:

==> set "A="

==> echo %A%
%A%

==> set A="qwerty" && echo %A%
%A%

==> echo %A%
"qwerty"

为什么要这样做?

SET命令最初是在1983年3月与MS-DOS 2.0一起引入的, 当时的内存和CPU非常有限,并且 每行一次的变量就足够了.

The SET command was first introduced with MS-DOS 2.0 in March 1983, at that time memory and CPU were very limited and the expansion of variables once per line was enough.

使用 CALL命令的解决方法:

==> set "A="

==> echo %A%
%A%

==> set A="qwerty" && CALL echo %A%
"qwerty"

为完整起见,以下批处理脚本详细说明了百分比扩展的机制及其与CALL命令的组合(请注意,批处理文件中的%百分号已加倍CALL Echo %%_var%%):

For the sake of completeness, the following batch script shows the mechanism of percent expansion and its combination with the CALL command in detail (note doubled % percent signs in the batch file CALL Echo %%_var%%):

@ECHO OFF
SETLOCAL
if NOT "%~1"=="" ECHO ON
echo        1st:
Set "_var=first"
Set "_var=second" & Echo %_var% & CALL Echo %%_var%%  
echo        2nd: 
Set "_var=first"
Set "_var=second" & CALL Echo %%_var%% & Echo %_var%  

输出,echo OFF:

Output, echo OFF:

==> D:\bat\SO\55237418.bat
       1st:
first
second
       2nd:
second
first

输出,echo ON:

Output, echo ON:

==> D:\bat\SO\55237418.bat on

==> echo        1st:
       1st:

==> Set "_var=first"

==> Set "_var=second"   & Echo first   & CALL Echo %_var%
first
second

==> echo        2nd:
       2nd:

==> Set "_var=first"

==> Set "_var=second"   & CALL Echo %_var%   & Echo first
second
first