Passing a variable to a remote host in a bash script with ssh and EOF [duplicate]

半世苍凉 提交于 2019-11-27 09:20:58

Use printf %q to escape content in an eval-safe form; after doing so, you can pass them on the command line of the remote shell, and retrieve them via $1, $2, etc. within the remote script:

# put contents of $VAR into $var_str in a format that a shell can interpret
printf -v var_str %q "$VAR"

#                                    v- pass the value on the shell command line
#                                    |           v- keep escaping the heredoc securely
#                                    |           |
ssh -T -p 1234 root@"$host" "bash -s $var_str" <<'EOF'

# retrieve it off the shell command line
var=$1

# ...and use it as you like thereafter.
echo "Remotely using $var"
EOF
Jahid

How about using EOF without the quote and making the mysql command work:

#!/bin/bash

# parsing servers
# defining one local variable $VAR
VAR=something

ssh -T -p 1234 root@"server-ip" <<EOF
# doing some stuff...
var_result=\$(mysql -hhost -uuser '-ppasswort' -Ddatabase -N -e "SELECT something FROM somewhere WHERE value=$VAR;")
EOF

As Charles Duffy stated, this may produce some security risk.

Another way is to wrap all your codes around single quote:

#!/bin/bash

# parsing servers
# defining one local variable $VAR

ssh -T -p 1234 root@"server-ip" '
# doing some stuff...
var_result=$(mysql -hhost -uuser "-ppasswort" -Ddatabase -N -e "SELECT something FROM somewhere WHERE value='"$VAR"';")
'

In this case you will have to be careful what you substitute your variables for. Better use Charles Duffys' method if you should be concerned about it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!