Script for finding resolv.conf file in /etc dir is not working

Hello Vivek,
I tried the script that you suggested but it didn’t work:

for file in /etc/*
do
        if [ "${file}" == "/etc/resolv.conf" ]
        then
                countNameServer=$(grep -c nameserver /etc/resolv.conf)
                echo "Total ${countNameServer} nameserver defined in ${file}"
        else
                break
        fi
done

The above script neither give any error nor any output. I have made this script under my /root/professional-script directory. When i used (/etc/resolv.conf in FOR loop it works however when i used {for file in /etc/* it didn’t}),i am in bit of confused now , any help would we appreciated

// Chinkleet

It is not working due to else. Remove else condition otherwise at first match for loop will die to due break:

for file in /etc/*
do
        if [ "${file}" == "/etc/resolv.conf" ]
        then
                countNameServer=$(grep -c nameserver /etc/resolv.conf)
                echo "Total ${countNameServer} nameserver defined in ${file}"
                break
        fi
done

You can verify that with the following:

bash -x your-script
bash -x -v your-script

HTH

There’s no possible reason why you would need to “search” in a loop. The file is either there or it’s not, so just reference it directly:

if [ -r /etc/resolv.conf ] ;then
   echo "The word nameserver is mentioned $(grep -c nameserver /etc/resolv.conf) times."
fi

Note: Finding the word nameserver, say, 5 times, doesn’t necessarily mean that you have 5 nameservers defined – the word may have been mentioned after a # comment.

And even better, this one counts the number of lines that actually start with the word “nameserver”:

n=$(( $(grep -cw '^nameserver' /etc/resolv.conf 2>/dev/null) ))
echo "Total of $n nameservers defined in /etc/resolv.conf"

Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki