How to Escape Character when Running SSH Remote Command

Tags: April 8, 2020 4:18 AM

Solution of Escaping Character on SSH

The solution is DO NOT escape it. Use cat HEREDOC to build the string of commands and then pass it to SSH.

$ export VARIABLE="FOO BAR"
$ cat <<EOF | ssh user@myserver bash
echo "This is complex command"
echo "Another command that take a $VARIABLE."
sudo mkdir /tmp/foo && echo "SUCCESS"
EOF

If you have a lot of $ dollar signs in your script and do not want local shell to interpret it then use single quote HEREDOC.

$ export VARIABLE_NAME="FOO BAR"
$ cat <<'EOF' | ssh user@myserver bash
export VARIABLE="SSH VAR"
echo "This is complex command"
echo "Another command that take a $VARIABLE name."
sudo mkdir /tmp/foo && echo "SUCCESS"
EOF

On command above the variable $VARIABLE value is "SSH VAR" since it is took the value from remote server not from local machine.

Share on Facebook Twitter

0 comments:

Post a Comment