Skip to content
Advertisement

How to have simple and double quotes in a scripted ssh command

I am writing a small bash script and want to execute the following command via ssh

JavaScript

Unfortunately this command contains both simple and double quotes so I can’t do

JavaScript

What would be the recommended way to solve this issue ?

Advertisement

Answer

Using a heredoc

You can just pass your exact code on the shell’s stdin:

JavaScript

Note that the above doesn’t perform any variable expansions — due to the use of <<'EOF' (vs <<EOF), it passes the code to the remote system exactly, so a variable expansion ("$foo") would be expanded on the remote side, using only variables available to the remote shell.

This also consumes stdin for the heredoc containing the script to be run — if you need stdin to be available for other purposes, that may not work as intended.


Generating an eval-safe command dynamically: Array Edition

You can also tell the shell itself to do the quoting for you. Assuming your local shell is bash or ksh:

JavaScript

The caveat there is that if your string expands to a value containing non-printable characters, the nonportable $'' quoting form may be used in the output of printf '%q'. To work around that in a portable manner, you actually end up using a separate interpreter such as Python:

JavaScript

Generating an eval-safe command dynamically: Function Edition

You can also encapsulate your command in a function, and tell your shell to serialize that function.

JavaScript

Using bash -s and passing code in a here-string or unquoted heredoc isn’t needed if you know with certainty that the remote shell is bash by default — if that were the case, you could pass the code on the command line (in place of the bash -s) instead.

If the remote command needs to be passed some variables, use declare -p to set them remotely in the same way the above uses using declare -f.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement