2

I would like to pass variable from node to shell command and execute it from node. How can I do that ?

1 Answer 1

0

From: http://www.dzone.com/snippets/execute-unix-command-nodejs

To execute shell commands:

var sys = require('sys')
var exec = require('child_process').exec;

exec('command', function (error, stdout, stderr) {});

From: Run shell script with node.js (childProcess),

To run a program bar.sh in your home folder with the argument 'foo':

var foo = 'foo';

exec('~/bar.sh ' + foo,
  function (error, stdout, stderr) {
    if (error !== null) {
      console.log(error);
    } else {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot. Now, how can I read this param in my .sh please
Arguments can be accessed in shell scripts with $X --- where X is the order the argument was passed. If your script bar.sh contains ´echo first param: $1, second param:$2´ It will print "first param: foo, second param:baz" when running ´sh bar.sh foo baz´ More info here
This has major security vulnerabilities if foo comes from a request or other source that untrusted users can control -- think about foo='$(rm -rf ~)'. The safe way to do it is to use execFile() with foo passed in the args list. That is, execFile("/path/to/bar.sh", [foo], function(error, stdout, stderr) { ... });
DO NOT FOLLOW THIS ANSWER. IT ALLOWS FOR SHELL SHOCK VULNERABILITY
@ShawnShroyer it's always more helpful to provide an alternative solution so others can learn. "Don't do XYZ" and not providing a viable alternative doesn't help newbies

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.