1

I have seen plenty of remarks on how to do this right, but somehow it does not work for me, and I am not sure why, some help would be appreciated.

Example Code:

#!/bin/bash
echo -en "\ec"
echo "."
#Dig MX Record
    DIG="$(which dig --skip-alias)"
    CurrentDomain="example.com"
    echo -n "${CurrentDomain} MX "
    CurrentMX="$(${DIG} ${CurrentDomain} MX +short)"
    readarray -t  ArrMX <<< "$CurrentMX";
    if [[ -n ${ArrMX[@]} ]]
    then
        printf '%s\n' "${ArrMX[@]}"
    else
        echo "No Entry"
    fi

As you can see this is only part of a Program that loops over a list, most of the values work, but when dig returns nothing cause it has no MX entry, I get MX: unbound variable yet I do the -z test...

Any suggestions?

Adesso
  • 928
  • 2
  • 13
  • 27

1 Answers1

2

Somewhere in your script you've set set -u which causes the shell to throw up errors when they are interpolated. As you've said in the case when dig fails, the CurrentMX variable is unset and when trying to access it in the read command to MX which is unset previously explicitly it throws the error.

Note that dig returns an empty result when it is not able to resolve a proper host. You could check that by just doing /usr/bin/dig example.com MX +short and compare it when you run with a proper host.

Also you seemed to have mixed-up the usage of arrays and variables in the read command, the -a flag of the read command takes in an array and not a variable.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    @Inian I had _set -o nounset_ at the top of my script causing the problem. As for my Array usage, dig will return all MX entries with linefeeds, so it should be a array... I'll improve the code a bit however ;) – Adesso Jul 18 '18 at 14:20