Home > Mobile >  How to chain CMD command to WSL in node-script
How to chain CMD command to WSL in node-script

Time:10-13

I've got a nodeserver and I'd like to start everything it depends on before launching it. The package runs on windows but depends on a multi-container docker setup in WSL.

So I've tried


  "scripts": {
    "start": "wsl 'sudo service docker start && docker-compose up -d' && nodemon server.js --config nodemon.json",
  },

but it throws

> Executing task: npm run start <

> wsl 'sudo service docker start && docker-compose up -d' && nodemon server.js --config nodemon.json

zsh:1: unmatched '
The terminal process "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command npm run start" terminated with exit code: 1.

What would be the correct syntax to do this?

CodePudding user response:

You do have mismatched quotes in there, but I'm assuming that's just an artifact of trying a bunch of different edits ;-).

The best way to pass a script (multiple commands) into the wsl command is to pass it to sh (or bash if needed). Taking just the WSL part for now, that would be:

wsl -e sh -c "sudo service docker start && docker-compose up -d"

From the error message you are getting, it looks like this is getting parsed through powershell.exe, which I don't believe supports && chaining. If I understand correctly, that's only available in PowerShell Core (pwsh.exe).

So that would make the full command (hopefully):

wsl -e sh -c "sudo service docker start && docker-compose up -d"; nodemon server.js --config nodemon.json

Quoting shouldn't be too bad on that, so hopefully:

"scripts": {
    "start": "wsl -e sh -c 'sudo service docker start && docker-compose up -d'; nodemon server.js --config nodemon.json",
  },

Not tested directly of course, but let me know if it doesn't work for you, and I can check out what I might have gotten wrong.

If you really do need to "chain" based on the previous commands being successful, then perhaps consider something like:

wsl -e sh -c "sudo service docker start && docker-compose up -d && powershell.exe nodemon server.js --config nodemon.json"

... which again, is pretty easy to quote. But if that doesn't work (or you end up needing more than one command that runs in PowerShell), then quoting starts to get much more difficult:

wsl -e sh -c "sudo service docker start && docker-compose up -d && powershell.exe -c \`"nodemon server.js --config nodemon.json\`""
  • Related