Using bash with Node.js child_process using the sh

2019-04-22 15:28发布

问题:

The child process api can be used to execute shell script in node.js.

Im using the child_process.exec(command[, options], callback) function

as an option the user of exec can set the shell: '/path/to/shell' field to select the shell to be used. (Defaults to '/bin/sh')

Setting options to {shell: '/bin/bash'} does not make exec runt the command with bash.

I have verified this by issuing the command "echo $0" which prints "/bin/sh".

How can I use bash with child_process.exec through the shell option?

(My goal is to make use of my path definitions in bashrc, now when i try to use grunt the binary cannot be found. Setting the cwd, current working directory in the options dictionary works as expected)

----------------- UPDATE, example

'use strict';
var cp = require('child_process');
cp.exec('echo $0', { shell: '/bin/bash' }, function(err, stdout, stderr){
    if(err){
        console.log(err);
        console.log(stderr);        
    }
    console.log(stdout);
});

Output:

/bin/sh

which bash

prints: /bin/bash

回答1:

Might be in your setup or passing options incorrectly in your code. Since you didn't post your code, it's tricky to tell. But I was able to do the following and it worked (using node 4.1.1):

"use strict";
const exec = require('child_process').exec

let child = exec('time',{shell: '/bin/bash'}, (err, stdout, stderr) =>     {
  console.log('this is with bash',stdout, stderr)
})
let child2 = exec('time',{shell: '/bin/sh'}, (err, stdout, stderr) => {
  console.log('This is with sh', stdout, stderr)
})

The output will be:

this is with bash  
real    0m0.000s
user    0m0.000s
sys 0m0.000s

This is with sh  /bin/sh: 1: time: not found

I used time as the command since it's one that bash has and sh does not. I hope this helps!