Gabriel Furstenheim
Gabriel Furstenheim

Reputation: 3432

Escape bash variable in node over ssh

When executing a bash command in node and passing a dynamic parameter, the standard way to go is to use spawn and avoid escaping. That is:

const filename = 'file with spaces'
spawn('ls', [filename]) // All good, received 'file with spaces'

This is foolproof since filename is passed as a standalone variable to bash.

Now, what happens if I want to do the same through ssh? The following is not an option:

const filename = 'file with spaces'
spawn('ssh', [host, 'ls', filename]) // Wrong!! Received 'file' 'with' 'spaces'

Ssh is accepting ls and filename as vargars. Joining it and executing, which defeats the purpose.

Upvotes: 0

Views: 474

Answers (1)

Gabriel Furstenheim
Gabriel Furstenheim

Reputation: 3432

One way is to pass the value using base64 which has expected characters and then escape in bash

spawn('ssh', [host, 'ls', `"$(echo ${btoa(filename)} | base64 -d)"`])

Upvotes: 1

Related Questions