Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo bash variable in node spawn command

Help me extrapolate bash variable value!

I've been googling around for some solutions, and thus far have not found an example of what I'm looking to do.

I've got a Jenkins job which is running a docker image containing a node runtime. During the creation of the docker image, some env vars were supplied (using export), which I would like to capture by spawning a child_process and using bash to extract the literal value the variable is pointing to.

For example, const child = child_process.spawn('echo', ['$var']);

I've tried every variation of quotes and escaping I can think of and I am not sure how to reference a bash variable from this command, invoked from inside a node script's spawned child process.

Please let me know if any of this is not clear. I have a preferred end solution, but it is blocked for now so I am trying to pursue this while we wait for the other solution to become available.

UPDATE FOR CLARITY - The env variable is stored in bash. You could normally access this by using echo $var. I am inside a bash shell running a node script, and I want to extrapolate the value to use in the node script by spawning a child process.

like image 541
Kraken Avatar asked Jul 29 '26 21:07

Kraken


2 Answers

In node you can access environment variables on global process object:

process.env.MY_ENV_VAR

In your case:

const child = child_process.spawn('echo', [process.env.var]);
like image 118
Andreas Louv Avatar answered Aug 01 '26 21:08

Andreas Louv


Use printenv instead of echo.

I had the same issue as you and the accepted answer here doesn't help. Not sure why it's accepted.

Try using printenv instead of echo to display the ENV value, like this:

const child = child_process.spawn( 'printenv', [ 'var' ] );
like image 37
Joshua Pinter Avatar answered Aug 01 '26 20:08

Joshua Pinter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!