2

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

Tushar
  • 880
  • 9
  • 17
Matthieu
  • 199
  • 2
  • 3
  • 15

1 Answers1

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);
    }
});
Community
  • 1
  • 1
krekle
  • 135
  • 6
  • 1
    Thanks a lot. Now, how can I read this param in my .sh please – Matthieu Jun 18 '15 at 14:26
  • 2
    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](http://osr600doc.sco.com/en/SHL_automate/_Passing_to_shell_script.html) – krekle Jun 18 '15 at 19:37
  • 4
    **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) { ... });` – Charles Duffy Apr 20 '18 at 15:24
  • DO NOT FOLLOW THIS ANSWER. IT ALLOWS FOR SHELL SHOCK VULNERABILITY – Shawn Shroyer Dec 23 '21 at 03:49
  • @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 – Christian Apr 06 '22 at 01:26