无法通过 SSH 在 heredoc 或命令中使用本地和远程变量

Hel*_*ves 4 linux ssh bash

下面是使用 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
Run Code Online (Sandbox Code Playgroud)

And*_*ini 5

$如果您不想扩展变量,则需要对符号进行转义:

$ 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
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下:

ssh user@host bash << EOF
# run script with output...
REMOTE_PID=$(cat $FILE_NAME)
echo \$REMOTE_PID
EOF
Run Code Online (Sandbox Code Playgroud)

或者,您可以只使用带单引号的 herestring:

$ x=abc
$ bash <<< '
> x=def
> echo $x  # This will not expand, because we are inside single quotes
> '
def
Run Code Online (Sandbox Code Playgroud)