0

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; }'`
2
  • 3
    It would be useful if you showed us what is the value in $MXrecords Commented Mar 18, 2013 at 19:22
  • Example, 10 mx1.parallels.com. 20 mx2.parallels.com. Commented Mar 18, 2013 at 20:01

2 Answers 2

1

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}')
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Unfortunately, it also leaves the same extra lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.