This project is actually so silly that I'll give you the solution right here (and explain). :P
What ssh does is connect to server1 and run the command with a shell ... After being parsed by the local shell. That means all special symbols are going to be parsed twice. In a way, this is pretty much the same as running
CMD
vs.
sh -c "CMD"
What's left cannot work because you're using single quotes the wrong way. So 'SELECT 'Column 1 text' as 'Column 1 Heading', table1.* FROM table1;' will be parsed as, in python terms,
['SELECT Column', '1', 'text as Column', '1', 'Heading'], whereas it is expected to be a single monolithic string.
What to do about this? The most simple fix is to explictly escape all shell-specific characters, eg. quotes, single quotes, semicolons etc, before passing them to the local shell. The trick is knowing which ones yes and which ones not.
Your call would be fixed by using this instead:
ssh server1 "mysql -u root -ppassword -e 'SELECT \"Column 1 text\" as \"Column 1 Heading\", table1.* FROM table1;' dataBase1"
You can also try to use this function for more generic conversion:
chars='[\"\ \t\&'\'']'
function convertInputForSsh() { for i in "${@}"; do echo -n $(echo ${i} | sed -e "s,\(${chars}\),\\\\\1,g")\ ; done; }
Example:
CMD=(for i in 1 '2 3' '4 5' 6\; do echo \${i}\; done)
> ssh server1 "${CMD[@]}"
1
2
3
4
5
6
vs.
> ssh server1 $(convertInputForSsh "${CMD[@]}")
1
2 3
4 5
6