Search code examples
bashparsingescapingsingle-quotes

How can I escape a single quote correctly in when using/parsing a remote variable?


I am trying to escape the following variable which is located on a remote server:

ssh root@$HWNODEIP "echo '    set root='$getgrub''   >> /etc/grub.d/40_custom"

In short I need to add a single quote before and after the variable $getgrub.

I tried several things like putting them in double quotes (") and escaping () it, however no luck. The only result I am getting is similar things like: "sed: -e expression #1, char 43: unknown option to `s'"

What am I doing wrong and what is the correct way to make this work? I also tried storing the $getgrub variable with single quotes included, however they don't appear in the file /etc/grub.d/40_custom?!

Probably I am making somewhere a mistake, but I cannot seem to find it.

Thanks.

//edit

If I run the following command from the server:

ssh root@$HWNODEIP  "echo '    set root='$getgrub'' >> /etc/grub.d/40_custom"

And I check the file the variable is in the file, however not with the single quotes in front and behind?

Output (cat) of the file:

set root=EXAMPLE

Where it should read:

set root='EXAMPLE'

Strange...


Solution

  • You need to escape the double quotes for echo:

    Example

    $ ssh user@server "echo \"set example='test'\" >> example.txt"
    

    Result (example.txt at the server)

    $ cat example.txt
    set example='test'