Hi can some one help me here on a shell script?
I have 2 hosts and 4 servers, I want to pass using for loop
host1 --> host1_server1 host1_server2
host2 --> host2_server1 host2_server2
I want to use a for
loop to print both sets, outputting both sets:
set 1 output
hostname : host1 servers: host1_server1
hostname : host1 servers: host1_server2
set 2 output
hostname : host2 servers: host2_server1
hostname : host2 servers: host2_server2
How can I achieve this using a Bash shell script?
One Bash solution is to use Bash arrays, Indirect References , and 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. From man bash
, see the printf
section:
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.