I am writing a small bash script and want to execute the following command via ssh
sudo -i mysql -uroot -pPASSWORD --execute "select user, host, password_last_changed from mysql.user where password_last_changed <= '2016-9-00 11:00:00' order by password_last_changed ASC;"
Unfortunately this command contains both simple and double quotes so I can't do
ssh user@host "command";
What would be the recommended way to solve this issue ?
Using a heredoc
You can just pass your exact code on the shell's stdin:
Note that the above doesn't perform any variable expansions -- due to the use of
<<'EOF'
(vs<<EOF
), it passes the code to the remote system exactly, so a variable expansion ("$foo"
) would be expanded on the remote side, using only variables available to the remote shell.This also consumes stdin for the heredoc containing the script to be run -- if you need stdin to be available for other purposes, that may not work as intended.
Generating an eval-safe command dynamically
You can also tell the shell itself to do the quoting for you. Assuming your local shell is bash or ksh:
The caveat there is that if your string expands to a value containing non-printable characters, the nonportable
$''
quoting form may be used in the output ofprintf '%q'
. To work around that in a portable manner, you actually end up using a separate interpreter such as Python: