Logan
Logan

Reputation: 7

get hostname from string using bash script

In my bash script I need to extract all hostnames from output of command for further ping:

for host in `echo $MXrecords | awk '{ printf "%s", $0; }'` ; do
    ping -c1 $host 2> /dev/null > /dev/null
    if [ "$?" -eq "0" ] ; then
        answ="OK"
    else
        answ="BAD"
    fi

    echo "\t$host [$answ]" 
done

But I have some extra string:

40 [BAD]
alt2.aspmx.l.google.com. [OK]
30 [BAD]
alt3.aspmx.l.google.com. [OK]

I get var MXrecords by means of dig:

MXrecords=`dig @$DNSserver $domainName IN MX +short +multiline | awk '{ printf "\t%s\n", $0; }'`

Upvotes: 0

Views: 1857

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185841

Try this instead :

for host in ${MXrecords##* }; do
    if ping -c1 $host &>/dev/null; then
        answ="OK"
    else
        answ="BAD"
    fi

    echo "\t$host [$answ]" 
done

Note

  • ${MXrecords##* } is a parameter expansion bash trick (a buil-tin)
  • &>/dev/null is a bash shorthand for >/dev/null 2>&1
  • The backquote (`) is used in the old-style command substitution. The foo=$(command) syntax is recommended instead. Backslash handling inside $() is less surprising, and $() is easier to nest. See http://mywiki.wooledge.org/BashFAQ/082
  • no need to test the special variable $?, you can use boolean logic like I do in my snippet

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200523

From the output it looks like $MXrecords contains the MX records including their priority:

40 alt2.aspmx.l.google.com.
30 alt3.aspmx.l.google.com.

Try replacing this:

`echo $MXrecords | awk '{ printf "%s", $0; }'`

with this:

$(echo "$MXrecords" | awk '{print $2}')

Upvotes: 1

Related Questions