I would like to pass variable from node to shell command and execute it from node. How can I do that ?
1 Answer
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);
}
});
5 Comments
Matthieu
Thanks a lot. Now, how can I read this param in my .sh please
Charles Duffy
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) { ... });Shawn Shroyer
DO NOT FOLLOW THIS ANSWER. IT ALLOWS FOR SHELL SHOCK VULNERABILITY
Christian
@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