linux - 如何将局部变量传递给 bash 脚本中的 ssh 作用域?

标签 linux bash ssh

我正在编写 bash 脚本,它必须通过 ssh 在远程服务器上执行一些命令。该脚本有两个主要部分:

第 1 部分: 使用局部变量 $A 和 $B

第 2 部分: 在远程服务器上执行命令如下:

ssh -T user@servername << 'EOF' ... Using local variables $A and $B ... EOF

问题是本地变量 $A 和 $B 在远程服务器上的 ssh 命令范围内不可用。据我了解,ssh 作用域外和内部的变量 $A 和 $B 是不一样的。

所以我的问题是如何将局部变量从 bash 脚本传递到 ssh 作用域? 另外请注意,第 2 部分非常大,所以我不能在 ssh 之后使用“one liner”。

谢谢

最佳答案

该问题与 ssh 无关,仅与 bash 或任何其他 Posix shell 中的此处文档有关。

bash 的手册页在此处的文档段落中说:

The format of here-documents is:

<<[-]word
here-document
delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and ` .

如您所言EOF ,您明确要求 shell 不要替换 $1$2变量。

最可靠的方法是不引用 EOF 并始终引用此处文档中的所有其他特殊字符。

例如,如果您的此处文档包含如下内容:

ssh -T user@servername << 'EOF'
for f in /var/log/messages*
do echo "Filename: " $f
done
EOF

你可以重写它,在 EOF 周围不加引号,但在 $ 中加一个引号:

ssh -T user@servername << EOF
for f in /var/log/messages*
do echo "Filename: " \$f
done
EOF

这样所有未引用的变量都会被插入。


或者,如果服务器允许,您可以尝试将 2 个参数作为环境变量传递。

假设您想使用名称 PARAM1PARAM2 . sshd_config服务器上的文件应包含 AcceptEnv PARAM1 PARAM2 行因为默认情况下并且出于安全原因,不接受任何环境变量。

然后您可以使用:

export PARAM1=$1
export PARAM2=$2
ssh -T -o SendEnv=PARAM1 -o SenEnv=PARAM2 user@servername  << 'EOF'
...
Using variables $PARAM1 and $PARAM2
...
EOF

关于linux - 如何将局部变量传递给 bash 脚本中的 ssh 作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39889701/

相关文章:

linux - 如何在 nginx.conf 中将 GitLab 配置为子域

regex - BASH:如何在 sed 命令中对字符串使用 Regex Negative Lookahead?

bash - 从文件中读取每一行并将其用作 curl 命令中的变量

苹果操作系统 : access SSH from UI

bash - sed命令无法通过SSH使用

linux - ssh2 中的特殊字符

linux - 打开文件过多错误,但 99.5% 的 inode 是免费的

c++ - 正则表达式适用于 Linux 但不适用于 Solaris

linux:通过 procfs 确定文件句柄标识

linux - 如何编写Shell脚本来设置默认参数