Search code examples
bashsshescapingquotesheredoc

How to properly escape double quotes in an ssh pkill bash command?


$ ssh [email protected]
123.123.123.123# pkill -f "stalled process name"; commands_to_restart; some_more_commands;
many many lines of output demonstrating success
123.123.123.123# exit;

ALL WORKS PERFECTLY

$ ssh [email protected] "pkill -f "\""stalled process name"\"";"\
> "commands_to_restart; some_more_commands;";

no output, DOES NOTHING.

$ ssh [email protected] "echo "\""pkill -f "\"\\\"\""stalled process name"\"\\\"\""; "\
> "commands_to_restart; some_more_commands;"\"";";
pkill -f "stalled process name"; commands_to_restart; some_more_commands;

so... TWO stages of quote escaping works as expected...

How do I get a single layer of quote escaping to work with ssh/bash? Since quoting works perfectly in two layers I have a feeling it has less to do with the quoting and more to do with some aspect of sshs handling of the terminal. Yet, as far as I know the commands do nothing but simple and regular IO to standard output and no input.


Solution

  • You are better off using a heredoc for such things:

    ssh [email protected] bash -s << 'EOF'
        pkill -f "stalled process name"
        commands_to_restart
        some_more_commands
    EOF
    
    • bash -s ensures that you are using bash and not the user-specific shell on the remote host
    • quoting the heredoc end marker ('EOF') ensures that the content is passed as-is, without the parent shell interpreting it