使用 shell 选项将 bash 与 Node.js child_process 一起使用失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32952410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using bash with Node.js child_process using the shell option fails
提问by user264230
The child process apican be used to execute shell script in node.js.
该子进程API可以用来执行node.js中的shell脚本
Im using the child_process.exec(command[, options], callback)function
我使用child_process.exec(command[, options], callback)函数
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')
作为一个选项,exec 的用户可以设置 shell: '/path/to/shell' 字段来选择要使用的 shell。(默认为'/bin/sh')
Setting options to {shell: '/bin/bash'} does not make exec runt the command with bash.
将选项设置为 {shell: '/bin/bash'} 不会使 exec 运行 bash 命令。
I have verified this by issuing the command "echo $0" which prints "/bin/sh".
我已经通过发出打印“/bin/sh”的命令“echo $0”验证了这一点。
How can I use bash with child_process.exec through the shell option?
如何通过 shell 选项将 bash 与 child_process.exec 一起使用?
(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)
(我的目标是在 bashrc 中使用我的路径定义,现在当我尝试使用 grunt 时找不到二进制文件。设置 cwd,选项字典中的当前工作目录按预期工作)
----------------- UPDATE, example
----------------- 更新,示例
'use strict';
var cp = require('child_process');
cp.exec('echo /bin/sh
', { shell: '/bin/bash' }, function(err, stdout, stderr){
if(err){
console.log(err);
console.log(stderr);
}
console.log(stdout);
});
Output:
输出:
which bash
"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)
})
prints: /bin/bash
打印:/bin/bash
回答by bbuckley123
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):
可能在您的设置中或在您的代码中错误地传递选项。由于您没有发布代码,因此很难说。但是我能够执行以下操作并且它有效(使用节点 4.1.1):
this is with bash
real 0m0.000s
user 0m0.000s
sys 0m0.000s
This is with sh /bin/sh: 1: time: not found
The output will be:
输出将是:
##代码##I used time
as the command since it's one that bash has and sh does not. I hope this helps!
我用作time
命令,因为它是 bash 有而 sh 没有的命令。我希望这有帮助!