16

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 Answer 1

16

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Works indeed, seems like the OP is on an older version of Node where this isn't supported (I had the same issue)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.