无法通过 SSH 在 heredoc 或命令中使用本地和远程变量 [英] Unable to use local and remote variables within a heredoc or command over SSH
问题描述
下面是一个使用 heredoc 的 ssh 脚本示例(实际脚本更复杂).是否可以在 SSH heredoc 或命令中同时使用本地和远程变量?
Below is an example of a ssh script using a heredoc (the actual script is more complex). Is it possible to use both local and remote variables within an SSH heredoc or command?
FILE_NAME
在本地服务器上设置,以便在远程服务器上使用.REMOTE_PID
在远程服务器上运行时设置,以便在本地服务器上使用.FILE_NAME
在脚本中被识别.REMOTE_PID
未设置.
FILE_NAME
is set on the local server to be used on the remote server. REMOTE_PID
is set when running on the remote server to be used on local server. FILE_NAME
is recognised in script. REMOTE_PID
is not set.
如果将 EOF
更改为 'EOF'
,则设置 REMOTE_PID
而不会设置 `FILE_NAME.我不明白这是为什么?
If EOF
is changed to 'EOF'
, then REMOTE_PID
is set and `FILE_NAME is not. I don't understand why this is?
有没有办法同时识别REMOTE_PID
和FILE_NAME
?
Is there a way in which both REMOTE_PID
and FILE_NAME
can be recognised?
正在使用 bash 的第 2 版.默认远程登录为cshell,本地脚本为bash.
Version 2 of bash being used. The default remote login is cshell, local script is to be 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
推荐答案
如果不想扩展变量,则需要转义 $
符号:
You need to escape the $
sign if you don't want the variable to be expanded:
$ 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
或者,您也可以只使用带单引号的此处字符串:
Or alternatively you can just use a herestring with single quotes:
$ x=abc
$ bash <<< '
> x=def
> echo $x # This will not expand, because we are inside single quotes
> '
def
这篇关于无法通过 SSH 在 heredoc 或命令中使用本地和远程变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!