gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:51:59 25 4
gpt4 key购买 nike

下面是一个使用 heredoc 的 ssh 脚本示例(实际脚本更复杂)。是否可以在 SSH heredoc 或命令中同时使用本地和远程变量?

FILE_NAME 在本地服务器上设置以在远程服务器上使用。 REMOTE_PID 在远程服务器上运行时设置为在本地服务器上使用。 FILE_NAME 在脚本中被识别。 REMOTE_PID 未设置。

如果 EOF 更改为 'EOF',则 REMOTE_PID 已设置,而 `FILE_NAME 未设置。我不明白这是为什么?

有没有办法同时识别REMOTE_PIDFILE_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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com