This works in the human brain, but the shell misses quoting:

for h in a b; do ssh $h psql -tAc "select * from mytab where mycol='x'"; done

How to quote this one liner without loosing readability?


You need to escape the quotes. Think of them as layers of wrapping, in a game of pass the parcel. Each shell unwraps a 'layer'.


echo "this ; is a semicolon"

But if you wanted to run that via ssh:

ssh $user@$host echo "this ; is a semicolon"

The ssh would unwrap the first layer of the package - sending:

echo this ; is a semicolon

Which would break, because semicolons are interpreted by the shell.

So to do this, you need to escape the quotes first - so ssh can 'unwrap' one layer safely:

ssh $user@$host echo "\"this ; is a semicolon\""

ssh will thus strip the 'outer'layer, and the 'escape' and pass through:

echo "this ; is a semicolon"

This will be what you need to do for your one liner. As for not losing readability - easier said than done I'm afraid, as escapes and quote nesting do inevitably get messy.

About the best I can offer is using a variable to encapsulate your SQL statement, so that it's at least clear that you're sending an 'encapsulated statement:

THING_TO_ECHO='"this ; is a semicolon"'; ssh $user@host echo $THING_TO_ECHO
  • I am missing the for loop in your answer. – guettli Apr 17 '15 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.