如何在Shell脚本中在远程服务器上使用带有远程变量的数组? [英] How to use an array with remote variable on remote server in shell scripting?

查看:298
本文介绍了如何在Shell脚本中在远程服务器上使用带有远程变量的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的...

This is what I am trying to do...

#!/bin/bash

array_local=(1 2 3 4 5)

ssh user@server << EOF
index_remote=1
echo \$index_remote
echo \${array_local[\$index_remote]}  
EOF

当我尝试运行上述脚本时,我得到的O/P为1和一个空值(空白).我希望$ {array_local [$ index_remote}]的值为2而不是null,我需要使用远程变量访问此本地数组,以便在脚本中进行进一步的工作.

When I try to run the above script I get the O/P as 1 and a null value (blank space). I wanted ${array_local[$index_remote} value to be 2 instead of null, I need to access this local array using remote variable for my further work in the script..

推荐答案

<<EOF导致变量扩展在本地计算机上发生,但是您仅在远程计算机上定义了变量i.您需要仔细考虑要在哪里进行扩展.您没有在问题中解释i的值是在客户端定义的,还是在服务器端定义的,但我从您的后续注释中猜测,您希望它在服务器端完成.在这种情况下,您需要将数组内容传递到ssh上,这需要仔细的引用:

<<EOF results variable expansion happening on the local machine, but you only defined the variable i on the remote machine. You need to think carefully about where you want to do the expansion. You haven't explained in your question whether the value of i is defined client-side or server-side, but I'm guessing from your subsequent comments that you want it done server-side. In that case you'll need to pass the array contents over ssh, which requires careful quoting:

ssh hostname@server <<EOF
i=1
eval `typeset -p array_local`
echo \${array_local[\$i]}
EOF

typeset -p array_local将输出字符串

declare -a array_local='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5")'

由于这是在反引号内,因此它将在EOF分隔的heredoc中得到扩展的客户端,然后由eval评估服务器端.换句话说,它等同于:

Since this is inside backticks, it will get expanded client-side within the EOF-delimited heredoc, and then evaluated server-side by the eval. In other words it's equivalent to:

ssh hostname@server <<'EOF'
i=1
declare -a array_local='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5")'
echo ${array_local[$i]}
EOF

请注意两个示例之间在EOF引用中的区别.第一个允许参数和shell扩展,第二个不允许.这就是为什么第一行中的echo行需要加引号,以确保参数扩展发生在服务器端而不是客户端.

Notice the difference in EOF quoting between the two examples. The first one allows parameter and shell expansion, and the second doesn't. That's why the echo line in the first one needs quoting, to ensure that parameter expansion happens server-side not client-side.

这篇关于如何在Shell脚本中在远程服务器上使用带有远程变量的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆