【问题标题】:Using bash with Node.js child_process using the shell option fails使用 shell 选项将 bash 与 Node.js child_process 一起使用失败
【发布时间】:2016-01-02 08:01:39
【问题描述】:

child process api 可用于在 node.js 中执行 shell 脚本。

我正在使用 child_process.exec(command[, options], callback) 函数

作为一个选项,exec 的用户可以设置 shell: '/path/to/shell' 字段来选择要使用的 shell。 (默认为“/bin/sh”)

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

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

如何通过 shell 选项将 bash 与 child_process.exec 一起使用?

(我的目标是在 bashrc 中使用我的路径定义,现在当我尝试使用 grunt 时找不到二进制文件。设置 cwd,选项字典中的当前工作目录按预期工作)

----------------- 更新,示例

'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

打印: /bin/bash

【问题讨论】:

    标签: node.js bash shell


    【解决方案1】:

    可能在您的设置中或在您的代码中错误地传递了选项。由于您没有发布代码,因此很难判断。但我能够执行以下操作并且它有效(使用节点 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 没有的命令。我希望这会有所帮助!

    【讨论】:

    • 确实有效,似乎 OP 在不支持此功能的旧版本 Node 上(我遇到了同样的问题)
    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 2013-05-22
    • 1970-01-01
    • 2017-02-11
    相关资源
    最近更新 更多