Instead of escaping things manually, you can ask the shell to do it for you and avoid the trouble (if your shell is bash; this is an extension not available in POSIX sh, so your shebang needs to be #!/bin/bash, not #!/bin/sh).
For instance:
printf -v command '%q ' /path/to/command arg1 arg2
printf -v outer_command '%q ' runasuser -l userNameHere -c "$command"
printf -v ssh_command '%q ' ssh hostname "$outer_command"
...will put a string in "$ssh_command" which, if evaluated, will run the inner command inside of runasuser inside ssh.
To provide some examples of how to use these variables, once constructed:
# this evaluates the command in the current shell in a sane way
ssh hostname "$outer_command"
# this evaluates the command in the current shell in an inefficient way
eval "$ssh_command"
# this evaluates the command in a new shell
bash -c "$ssh_command"
# this evaluates the command in a new shell as a different user
sudo -u username bash -c "$ssh_command"
# this writes the command to a script, and makes it executable
printf '%s\n' "#!/bin/bash" "$ssh_command" >run_ssh
chmod +x run_ssh
To provide some counterexamples of how NOT to use these variables, once constructed:
# DO NOT DO THESE: WILL NOT WORK
$ssh_command # see http://mywiki.wooledge.org/BashFAQ/050
"$ssh_command" # likewise
sudo "$ssh_command" # likewise