2015-10-05 92 views
5

child process api可用于在node.js中执行shell脚本。使用bash和Node.js的child_process使用shell选项失败

林使用child_process.exec(命令[,选项],回调)函数

作为一个选项EXEC的用户可以设置外壳:“/路径/到/壳”字段来选择外壳被使用。 (默认为'/ bin/sh')

将选项设置为{shell:'/ bin/bash'}不会使exec用bash命令执行命令。

我已通过发出打印“/ bin/sh”的命令“echo $ 0”验证了这一点。

如何通过shell选项使用带有child_process.exec的bash?

(我的目标是利用我的路径定义中的.bashrc,现在当我尝试使用咕噜二进制无法找到。设置的选项预期词典作品CWD,当前工作目录)

----------------- UPDATE,例如

'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); 
}); 

输出:

/bin/sh 

which bash 

打印: /斌/庆典

回答

3

可能是在你的安装或不正确地传递选项在你的代码。既然你没有发布你的代码,这很难说。但是我能做到以下几点,它的工作(使用节点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) 
}) 

输出将是:

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

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

我以前time的命令,因为它是一个bash有而sh不会。我希望这有帮助!

+0

工作确实,似乎OP是在一个旧版本的节点,这是不支持的(我有同样的问题) – Yousef