4

I have found a difference in how my node.js shell script works in Windows vs Linux. I have a string of commands that are synchronously executed using the child_process library.

var cmd = `echo 'hello'
echo 'Stack'
echo 'Overflow'`

var exec = require('child_process').execSync;
var options = {
  encoding: 'utf8'
};
console.log(exec(cmd, options));

In Linux

This executes all 3 echo statements and outputs as I expect it to.

hello
Stack
Overflow

In Windows

Whereas in Windows, I don't know if it executes 3 times or not. All I do know is that only the first echo command is outputted.

hello

Why am I seeing this difference and can I fix it so that the Windows script outputs similar to the way it does on Linux?

torek
  • 448,244
  • 59
  • 642
  • 775
Cameron
  • 2,805
  • 3
  • 31
  • 45
  • just out of curiosity, what happens when you change `cmd` to `var cmd = "echo 'hello' && echo 'Stack' && echo 'Overflow'"`? – zoecarver May 25 '17 at 01:14
  • Not sure tbh. I could try it when I get back to my computer (on my phone) – Cameron May 25 '17 at 01:15
  • 1
    That would be great! I would try it, but I do not have a windows computer easily accessible at the moment. – zoecarver May 25 '17 at 01:21
  • I tested that and it works! If you have a good explanation as to why I will happily award best answer! – Cameron May 25 '17 at 01:54
  • I am not exactly sure why it works, but I can take a guess. If you don't mind, what is the output of your code with `\n` after every line? – zoecarver May 25 '17 at 02:25
  • If I do var `cmd = \`echo 'hello'\necho 'Stack'\necho 'Overflow'\n\`` it will return `'hello'` – Cameron May 25 '17 at 02:31

2 Answers2

3

You should use:

var cmd = "echo 'hello' && echo 'Stack' && echo 'Overflow'"

instead of

var cmd = `echo 'hello'
echo 'Stack'
echo 'Overflow'`

I am not quite sure why this works but I have a guess.

&& executes this command only if previous command's errorlevel is 0.

Which means that it treats each line as separate commands. Whereas in your way, it (probably) treats each line as the same command, and for whatever reason this causes it to only output the first line.

zoecarver
  • 5,523
  • 2
  • 26
  • 56
1

Could it be that the script was created in linux and therefore it has LF (LineFold) \n line-endings? windows on the other hand expects CRLF (CarrageReturn LineFold) \r\n.

When you change the line-ending in your editor of choice to windows-style line endings, I bet it will work.

ShabbY
  • 896
  • 5
  • 9
  • I feel like that's the most logical explanation, but I've switched the code to both LF and CLRF and neither have worked. – Cameron May 25 '17 at 02:38