且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用ssh和EOF在bash脚本中将变量传递给远程主机

更新时间:2022-02-03 04:25:16

使用printf %qeval安全形式转义内容;之后,您可以在远程外壳程序的命令行上传递它们,并通过$1$2等在远程脚本中检索它们:

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