0

Inlining the env works SOMETHING=hello node -e "console.log(process.env.SOMETHING)", but I want node to read the environment variables from the spawning shell.

The following code will print hello (note that echo can read the environment)

SOMETHING=hello
echo $SOMETHING

However the following code prints undefined:

SOMETHING=hello
node -e "console.log(process.env.SOMETHING)"

Why can't node read the shell environment? Can I make it read that somehow?

3
  • You have set a shell variable SOMETHING, but not an environment variable. By default, shell variables don't go into the environment. Commented Sep 9, 2021 at 7:50
  • I remeoved the node.js tag, because the question is not really related to Node.js. You would run into the same problem if you would just use a bash subshell: FOO=x; bash -c 'echo ${FOO:-undefined}' prints undefined. Commented Sep 9, 2021 at 7:53
  • In echo $SOMETHING, the echo command is not getting the value of SOMETHING from the environment, the shell is expanding the variable and then passing the result to echo. Commented Sep 9, 2021 at 9:58

1 Answer 1

1

Run like this:

export SOMETHING=hello
node -e "console.log(process.env.SOMETHING)"

OR

SOMETHING=test node -e "console.log(process.env.SOMETHING)"
Sign up to request clarification or add additional context in comments.

1 Comment

2nd example is fixed now by @Moshe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.