下面是一个使用 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
关于linux - 无法通过 SSH 在 heredoc 或命令中使用本地和远程变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43483464/