下面是一个使用heredoc的ssh脚本的例子(实际的脚本更复杂)。是否可以在 SSH heredoc 或命令中同时使用局部和远程变量?
FILE_NAME
在本地服务器上设置,以便在远程服务器上使用。REMOTE_PID
是在远程服务器上运行时设置的,以在本地服务器上使用。FILE_NAME
在脚本中被识别。REMOTE_PID
未设置。
如果EOF
更改为'EOF'
,则设置REMOTE_PID
,而 'FILE_NAME 不设置。我不明白这是为什么?
有没有一种方法可以识别REMOTE_PID
和FILE_NAME
?
正在使用的 bash 版本 2。默认远程登录为 cshell,本地脚本为 bash。
FILE_NAME=/example/pdi.dat
ssh user@host bash << EOF
# run script with output...
REMOTE_PID=$(cat $FILE_NAME)
echo $REMOTE_PID
EOF
echo $REMOTE_PID
如果您不希望扩展变量,则需要转义$
符号:
$ x=abc
$ bash <<EOF
> x=def
> echo $x # This expands x before sending it to bash. Bash will see only "echo abc"
> echo $x # This lets bash perform the expansion. Bash will see "echo $x"
> EOF
abc
def
所以在你的情况下:
ssh user@host bash << EOF
# run script with output...
REMOTE_PID=$(cat $FILE_NAME)
echo $REMOTE_PID
EOF
或者,您也可以只使用带有单引号的此处字符串:
$ x=abc
$ bash <<< '
> x=def
> echo $x # This will not expand, because we are inside single quotes
> '
def
remote_user_name=user
instance_ip=127.0.0.1
external=$(ls /home/)
ssh -T -i ${private_key} -l ${remote_user_name} ${instance_ip} << END
internal=$(ls /home/)
echo "${internal}"
echo "${external}"
END