ssh 远程变量赋值?

ssh 远程变量赋值?

问题描述:

以下对我不起作用:

ssh user@remote.server "k=5; echo $k;"

它只返回一个空行.

如何在远程会话 (ssh) 上分配变量?

How can I assign a variable on a remote session (ssh)?

注意:我的问题不是关于如何将局部变量传递给我的 ssh 会话,而是关于如何创建和分配远程变量.(应该是一个非常简单的任务?)

Note: My question is not about how to pass local variables to my ssh session, but rather how to create and assign remote variables. (should be a pretty straight forward task?)

更详细地说,我正在尝试这样做:

In more detail I am trying to do this:

bkp=/some/path/to/backups
ssh user@remote.server "bkps=( $(find $bkp/* -type d | sort) );
                        echo 'number of backups: '${#bkps[@]};
                        while [ ${#bkps[@]} -gt 5 ]; do
                            echo ${bkps[${#bkps[@]}-1]};
                            #rm -rf $bkps[${#bkps[@]}-1];
                            unset bkps[${#bkps[@]}-1];
                        done;"

find 命令工作正常,但由于某种原因 $bkps 没有被填充.所以我的猜测是这将是一个变量分配问题,因为我认为我已经检查了其他所有内容......

The find command works fine, but for some reason $bkps does not get populated. So my guess was that it would be a variable assignment issue, since I think I have checked everything else...

鉴于此调用:

ssh user@remote.server "k=5; echo $k;"

本地 shell 在执行 ssh ... 之前正在扩展 $k(很可能没有设置).因此,一旦建立连接,实际传递给远程 shell 的命令是 k=5;echo ; (或 k=5; echo something_else_entirely; 如果 k 实际上是在本地设置的).

the local shell is expanding $k (which most likely isn't set) before it is executing ssh .... So the command that actually gets passed to the remote shell once the connection is made is k=5; echo ; (or k=5; echo something_else_entirely; if k is actually set locally).

为避免这种情况,请像这样转义美元符号:

To avoid this, escape the dollar sign like this:

ssh user@remote.server "k=5; echo \$k;"

或者,使用单引号而不是双引号来防止局部扩展.然而,虽然这适用于这个简单的示例,但您实际上可能希望在发送到远程端的命令中对某些变量进行本地扩展,因此反斜杠转义可能是更好的方法.

Alternatively, use single quotes instead of double quotes to prevent the local expansion. However, while that would work on this simple example, you may actually want local expansion of some variables in the command that gets sent to the remote side, so the backslash-escaping is probably the better route.

为了将来参考,您还可以在 shell 中键入 set -x 以回显正在执行的实际命令,以帮助进行故障排除.

For future reference, you can also type set -x in your shell to echo the actual commands that are being executed as a help for troubleshooting.