linux - How to have simple and double quotes in a scripted ssh command -


i writing small bash script , want execute following command via ssh

sudo -i mysql -uroot -ppassword --execute "select user, host, password_last_changed mysql.user password_last_changed <= '2016-9-00 11:00:00' order password_last_changed asc;" 

unfortunately command contains both simple , double quotes can't do

ssh user@host "command"; 

what recommended way solve issue ?

using heredoc

you can pass exact code on shell's stdin:

ssh user@host bash -s <<'eof' sudo -i mysql -uroot -ppassword --execute "select user, host, password_last_changed mysql.user password_last_changed <= '2016-9-00 11:00:00' order password_last_changed asc;" eof 

note above doesn't perform variable expansions -- due use of <<'eof' (vs <<eof), passes code remote system exactly, variable expansion ("$foo") expanded on remote side, using variables available remote shell.

this consumes stdin heredoc containing script run -- if need stdin available other purposes, may not work intended.


generating eval-safe command dynamically

you can tell shell quoting you. assuming local shell bash or ksh:

#!/usr/bin/env bash #              ^^^^ - not /bin/sh  # put command array, honoring quoting , expansions cmd=(   sudo -i mysql -uroot -ppassword     --execute "select user, host, password_last_changed mysql.user password_last_changed <= '2016-9-00 11:00:00' order password_last_changed asc;" )  # generate string evaluates array when parsed shell printf -v cmd_str '%q ' "${cmd[@]}"  # pass string remote host ssh user@host "$cmd_str" 

the caveat there if string expands value containing non-printable characters, nonportable $'' quoting form may used in output of printf '%q'. work around in portable manner, end using separate interpreter such python:

#!/bin/sh # works posix-compliant shell, either locally or remotely # ...it *does* require python (either 2.x or 3.x) on local end.  quote_args() { python -c ' import pipes, shlex, sys quote = shlex.quote if hasattr(shlex, "quote") else pipes.quote sys.stdout.write(" ".join(quote(x) x in sys.argv[1:]) + "\n") ' "$@"; }  ssh user@host "$(quote_args sudo -i mysql -uroot -ppassword sudo -i mysql -uroot -ppassword)" 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -