Using bash with Node.js child_process using shell option fails

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

I am using child_process.exec (command [, options], callback) function

as an option, the user user can set the shell: '/ path / to / shell' to select the shell to be used. (The default is "/ bin / sh")

The settings for {shell: '/ bin / bash'} do not make exec runt a command with bash.

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

How to use bash with child_process.exec through shell?

(My goal is to use path definitions in bashrc, now when I try to use grunt, the binary cannot be found. Installing cwd, the current working directory in the parameter 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: / ben / bash

+5
source share
1 answer

You may have incorrectly specified your settings or transfer parameters in your code. Since you have not published your code, it is difficult to describe. 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 a command, since it has bash and sh is not. Hope this helps!

+3
source

Source: https://habr.com/ru/post/1232985/


All Articles