无法在Heredoc或通过SSH的命令中使用本地和远程变量 [英] 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
?
正在使用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
或者,您也可以只使用带单引号的herestring:
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
这篇关于无法在Heredoc或通过SSH的命令中使用本地和远程变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!