I've solved this problem with the following 2 POSIX functions.
https://mullikine.github.io/posts/missing-posix-shell-functi...
cmd() { for var in "$@"; do printf "'%s' " "$(printf %s "$var" | sed "s/'/'\\\\''/g")"; done | sed 's/ $//'; }
myeval() { eval "$(cmd "$@")"; }
`cmd` is by far the most useful of the two. It returns the arguments it was given, properly escaped. You can use it to capture the arguments as a string and then pass them to ssh. # The following captures the arguments to the running script as a string.
CMD="$(cmd "$@")"
# Another example, could be putting some command into a string.
CMD="$(cmd echo "This will run on the server")"
# Then you run ssh as follows.
ssh remotehost "$CMD"
# Or something like this.
ssh remotehost "$(cmd echo "This will run on the server")"
The real power is in nesting! ssh remotehost "$(cmd echo "This will run on the server" "$(cmd "Now I don't need" "to worry" "$(cmd About "escaping escapes")")")"
That will generate these escapes. 'ssh' 'remotehost' ''\''echo'\'' '\''This will run on the server'\'' '\'''\''\'\'''\''Now I don'\''\'\'''\''\'\''\'\'''\'''\''\'\'''\''t need'\''\'\'''\'' '\''\'\'''\''to worry'\''\'\'''\'' '\''\'\'''\'''\''\'\'''\''\'\''\'\'''\'''\''\'\'''\''About'\''\'\'''\''\'\''\'\'''\'''\''\'\'''\'' '\''\'\'''\''\'\''\'\'''\'''\''\'\'''\''escaping escapes'\''\'\'''\''\'\''\'\'''\'''\''\'\'''\'''\''\'\'''\'''\'''