Home » How To » BASH: How to retrieve multiple ip addresses for a host name and put them into a BASH array

BASH: How to retrieve multiple ip addresses for a host name and put them into a BASH array

BASH‘s read has the capability of stuffing an array (ip_addresses) with the tokenized STDIN. The three less than signs “<<<" tells BASH to redirect the stdout output of the following statement. [bash highlight_lines="9"]#!/bin/bash servers=( pop.bizmail.yahoo.com smtp.bizmail.yahoo.com forums.sybase.com ) for server in ${servers[@]}; do # declare that variable ip_addresses is an array. not strictly needed but makes it a bit more readable IMHO declare -a ip_addresses read -a ip_addresses <<< $( host $server | awk ' $3 == "address" { print $4 } ' ) for ip in ${ip_addresses[@]}; do sudo route add -host ${ip} gw 192.168.0.1 dev bnep0 done done[/bash] We can see the output of the script: [text]pop.bizmail.yahoo.com is 68.142.224.70 pop.bizmail.yahoo.com is 209.191.119.134 pop.bizmail.yahoo.com is 68.142.198.20 smtp.bizmail.yahoo.com is 206.190.48.12 smtp.bizmail.yahoo.com is 68.142.200.11 forums.sybase.com is 192.138.151.106[/text]

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

Facebook login by WP-FB-AutoConnect