Using quotes in remote commands

In my previous tutorial I showed how to escape quotes in Bash and PowerShell commands. So far so good. Now what if you want to execute a Bash command via SSH from a PowerShell instance?

Let’s start with the plain Bash command we want to execute:

echo $'Hello \' world!'

This executed on Bash includes a single quote in the string. Please note the three single quotes in the command. Now to execute ssh on PowerShell on Windows we can use the following command:

PS> ssh ago@server-0003 'YOUR_COMMAND_GOES_HERE'

I spared the actual command in this line to show how this needs to “treated” in order to be executed remotely. Now we know from the previous tutorial that each single quote needs to be replaced with two single quotes in order to be recognized as string character and not as delimiting character. For the shown Bash command this would mean this:

echo $''Hello \'' world!''

Now we can replace “YOUR_COMMAND_GOES_HERE” with the treated command and this would be this:

ssh ago@server-0003 'echo $''Hello\''world!'''
Green: PowerShell, Red: Bash, Selected: Gets replaced with ‘ by PowerShell

I hope this helps somebody.