简体   繁体   English

Shell脚本在for循环中接受多组数组

[英]shell script to accept multiple sets of arrays in for loop

Hi can some one help me here on a shell script? 嗨,有人可以在shell脚本上帮我吗?

I have 2 hosts and 4 servers, I want to pass using for loop 我有2台主机和4台服务器,我想通过使用for循环

host1 -->  host1_server1 host1_server2 
host2 -->  host2_server1 host2_server2 

I want to use a for loop to print both sets, outputting both sets: 我想使用for循环打印两个集合,输出两个集合:

set 1 output 设置1个输出

hostname : host1 servers: host1_server1
hostname : host1 servers: host1_server2

set 2 output 设置2输出

hostname : host2 servers: host2_server1
hostname : host2 servers: host2_server2

How can I achieve this using a Bash shell script? 如何使用Bash Shell脚本实现此目标?

One Bash solution is to use Bash arrays, Indirect References , and printf . 一种Bash解决方案是使用Bash数组, 间接引用printf

#!/bin/bash

declare -a hosts=(host1 host2)     # array of variable names; quoting not needed

declare -a host1=("host1_server1" "host1_server2")
declare -a host2=("as-host2_server1" "as-host2_server2")

for Host in "${hosts[@]}"; do
   Indirect="$Host[@]"
   printf "hostname : $Host servers: %s\n" "${!Indirect}"
done

The above generates the following output: 上面产生了以下输出:

hostname : host1 servers: host1_server1
hostname : host1 servers: host1_server2
hostname : host2 servers: as-host2_server1
hostname : host2 servers: as-host2_server2

This solution also takes advantage of the printf command's behavior to reuse the format to consume all of the arguments. 此解决方案还利用了printf命令的行为来重用格式以使用所有参数。 From man bash , see the printf section: man bash ,请参见printf部分:

The format is reused as necessary to consume all of the arguments 该格式可根据需要重新使用以消耗所有参数

As a point of interest, note that the Bash idiom "${Variable[@]}" preserves any spaces within array elements. 有趣的是,请注意Bash习惯用法"${Variable[@]}"保留数组元素内的所有空格。 Also, if there are no elements in the array, this idiom expands to nothing. 同样,如果数组中没有元素,则该惯用法扩展为空。 This in many circumstances is very useful. 这在许多情况下非常有用。

These approaches, combined, allow for a single for loop to accomplish what you are asking for. 这些方法结合在一起,可以实现一个for循环来完成您所要求的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM