string passed to execSync has new line and I want to execute the string as a single command

Viewed 41

I want to pass the execSync function of node.js a string that is not in a line (I mean it has a number of new lines). for example:

require('child_process').execSync(`echo hello 
world 
to
all > /home/kali/Desktop/output`);

but I have the below error:

/bin/sh: 2: world: not found
node:child_process:903
    throw err;
    ^

Error: Command failed: echo hello 
world > /home/kali/Desktop/output
/bin/sh: 2: world: not found

    at checkExecSyncError (node:child_process:826:11)
    at Object.execSync (node:child_process:900:15)
    at Object.<anonymous> (/home/kali/Desktop/vm_escape.js:36:26)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47 {
  status: 127,
  signal: null,
  output: [
    null,
    Buffer(6) [Uint8Array] [ 104, 101, 108, 108, 111, 10 ],
    Buffer(29) [Uint8Array] [
       47,  98, 105, 110,  47, 115, 104,
       58,  32,  50,  58,  32, 119, 111,
      114, 108, 100,  58,  32, 110, 111,
      116,  32, 102, 111, 117, 110, 100,
       10
    ]
  ],
  pid: 216244,
  stdout: Buffer(6) [Uint8Array] [ 104, 101, 108, 108, 111, 10 ],
  stderr: Buffer(29) [Uint8Array] [
     47,  98, 105, 110,  47, 115, 104,
     58,  32,  50,  58,  32, 119, 111,
    114, 108, 100,  58,  32, 110, 111,
    116,  32, 102, 111, 117, 110, 100,
     10
  ]
}

it is because of new lines. it doesn't execute "echo hello world to all > /home/kali/Desktop/output" as a single command. but It executes the "echo hello", "world", "to", and "all" commands so I have errors. because of some limitations in my project I can't use double quotation and quotation inside back quote. what should I do?

edited:

new line is the delimiter for execSync. is there any way to change the delimiter in execSync? or is there any alternative for execSync that its delimiter is not new line?

1 Answers

you should be able to remove the line breaks with a replace

require('child_process').execSync(`echo hello 
world 
to
all > /home/kali/Desktop/output`.replace(/(\r\n|\n|\r)/gm, ``));

which would be equivalent to running

require('child_process').execSync(`echo hello world to all > /home/kali/Desktop/output`);
Related