How do I escape a string for a shell command in node?

前端 未结 6 1851
粉色の甜心
粉色の甜心 2020-12-01 05:04

In nodejs, the only way to execute external commands is via sys.exec(cmd). I\'d like to call an external command and give it data via stdin. In nodejs there does yet not app

6条回答
  •  忘掉有多难
    2020-12-01 05:34

    If you need simple solution you can use this:

    function escapeShellArg (arg) {
        return `'${arg.replace(/'/g, `'\\''`)}'`;
    }
    

    So your string will be simply escaped with single quotes as Chris Johnsen mentioned.

    echo 'John'\''s phone';
    

    It works in bash because of strong quoting, feels like it also works in fish, but does not work in zsh and sh.

    If you have bash your can run your script in sh or zsh with 'bash -c \'' + escape('all-the-rest-escaped') + '\''.

    But actually... node.js will escape all needed characters for you:

    var child = require('child_process')
      .spawn('echo', ['`echo 1`;"echo $SSH_TTY;\'\\0{0..5}']);
    
    child.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });
    
    child.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    

    this block of code will execute:

    echo '`echo 1`;"echo $SSH_TTY;'\''\\0{0..5}'
    

    and will output:

    stdout: `echo 1`;"echo $SSH_TTY;\'\\0{0..5}
    

    or some error.

    Take a look at http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

    By the way simple solution to run a bunch of commands is:

    require('child_process')
      .spawn('sh', ['-c', [
        'cd all/your/commands',
        'ls here',
        'echo "and even" > more'
      ].join('; ')]);
    

    Have a nice day!

提交回复
热议问题