The Shell lost the inverted comma in a nested ssh command

Hi,

i want use this Comand for my psql request

sh ssh -o StrictHostKeyChecking=no rootatemailaddress.de sudo psql -U postgres -c "select pg_terminate_backend(pid) from pg_stat_activity where datnam=\'$DB\';"'"

but the shell lost the inverted comma for datnam=\'$DB\' . The request deliver datnam=DB1 but for the psql request i need datnam='DB' . Where is my mistake? The psql comand need the inverted comma left and right from the $DB variable.

Quite involved a remote command. I can't replicate your entire setup, but for a simplified command, dropping the sh from the front, and removing the '" from the end made it work. Give it a try?

Could you try these variations?:-

ssh -o StrictHostKeyChecking=no rootatemailaddress.de 'sudo psql -U postgres -c "select pg_terminate_backend(pid) from pg_stat_activity where datnam=\'$DB\';"'"'       # Wrapping it all in single quotes should pass the double quotes, but you may need to escape the single quotes within the double quotes
ssh -o StrictHostKeyChecking=no rootatemailaddress.de 'sudo psql -U postgres -c \'select pg_terminate_backend(pid) from pg_stat_activity where datnam=$DB;\''             # backslash and two single quotes at the end
ssh -o StrictHostKeyChecking=no rootatemailaddress.de "sudo psql -U postgres -c \"select pg_terminate_backend(pid) from pg_stat_activity where datnam=\"\$DB\";\""       # backslash and two double quotes at the end, escaping the $ for the DB name
ssh -o StrictHostKeyChecking=no rootatemailaddress.de "sudo psql -U postgres -c \"select pg_terminate_backend(pid) from pg_stat_activity where datnam=\\\"\$DB\\\";\""     # extra escaping so that the quoted string passed ends up as \"$DB\" to the remote shell.
ssh -o StrictHostKeyChecking=no rootatemailaddress.de "sudo psql -U postgres -c \"select pg_terminate_backend(pid) from pg_stat_activity where datnam=\"\$DB\";\""       # Which seems to work okay if I insert an echo before the sudo (because I don't have postgress installed on my local machine.

They are variations to try passing quotes and/or quoted text. I presume that you want to pick up the value of $DB from the remote machine rather than the local machine.

Does that get you anywhere? If you want to just dummy run it, add an echo just before the sudo within the quotes (of whatever type) and it should show you what it would run on the remote machine. Where do you pick up the vale of $DB ? Is that set in the profile of the account you are connecting to? Should we worry that the sudo command has no password requirement?

I hope that this helps,
Robin