3

we can run command via ssh:

$ ssh user@host bash -c "'echo x '"
x

However I found that I cannot escape ':

$ ssh user@host bash -c "'echo \''"
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file

I also tried \\ and \\\, \\\\, nothing works.

the idea is to pass things like ls -1tr /var/log/ | head -10 | xargs -d '\n' -I {} echo {}. But the \' does not work so I do not know how to pass the '\n'. How can I achieve this?

Wang
  • 1,296
  • Try doubling your backslash. It will pass a single backslash down one level of interpretation. – waltinator Feb 12 '21 at 15:16
  • Does this answer your question? https://unix.stackexchange.com/questions/450020/executing-sh-c-script-through-ssh-passing-arguments-safely-and-sanely – Kusalananda Feb 12 '21 at 15:23
  • To quote a string that includes single quotes you can escape the single quotes outside pairs of single quotes with a backslash, e.g. for foo'bar use 'foo'\''bar'. You might have to double the backslashes. Try "'ls -1tr /var/log/ | head -10 | xargs -d '\\''\\n'\\'' -I {} echo {}'". – Bodo Feb 12 '21 at 15:25

2 Answers2

6

When you find yourself in quoting hell, heredocs often help

ssh user@host bash <<END
echo \'
END

That being said, there is no way for a single quoted string to contain a single quote

glenn jackman
  • 85,964
  • 1
    The limitation is that if the passed script needs to do user interaction, the standard input is now used by the script itself. Also, you don't need to invoke bash explicitly if the remote shell is bash (we don't know what the remote shell is though). – Kusalananda Feb 12 '21 at 16:22
1

GNU Parallel internally quotes strings multiple times. You can use the quoting engine with:

$ parallel --shellquote
write your string here, which may contain ' or " or \n
ctrl-D

If you need it quoted twice:

parallel --shellquote --shellquote

For fun:

echo "'" | parallel --shellquote --shellquote --shellquote --shellquote --shellquote --shellquote
Ole Tange
  • 35,514