Search code examples
npm-scripts

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


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

> [email protected] 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  

> [email protected] baz
> sh -c 'VAR=$(echo hello) echo $VAR'


$ echo $?
0

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


Solution

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

     VAR=$(echo hello); echo $VAR
    
     >>> hello