Bash script to change Name servers on BIND DNS Zones in CentOS7/RHEL7

DNS is one of the most important components of web hosting. It resolves addresses which allows websites to be accessed online via domain names and emails to be sent/received.

Due to this importance, we decided to consolidate our DNS to 3 powerful name servers. Our task was split into 2 parts:

1. Updating the name servers in zone files.

2. Updating the name servers on the domains.

Name server update on the domain was not difficult as this is provided for in registry portals.

As for the zone files, we needed to develop a script to accomplish this. We needed the script to replace the current existing 2 name servers with 2 new ones, then add a third one as we now used three name servers to provide enough redundancy. All our name servers run on BIND.

Below is the script we developed to accomplish the task.

Note: Before running this script, please backup your zone files directory just in case of anything. One can never under estimate the importance of a backup!

#Bash script to update nameservers
for file in *.db; do
    base=$(basename "$file" '.db')
    sed -i
"s/" /var/named/$file
    sed -i
"s/" /var/named/$file
    sed -i '/ '$base.'  
86400   IN      NS' /var/named/$file

The Script Explained

Basically, the following is what the script does. It should be run from inside the folder where zone files are stored.

– It loops through all files that end with .db e.g.

– Anytime it opens a file:

– It finds any instance of the first name server,, and replaces with a new one This is repeated for as well.

– With the two original domains replaced, a third one needs to be added. So line 8 in the script adds the third name server,, below the line that has

The option -i given to sed command makes sed write the changes to the file. Otherwise, it just displays the file with the changes but doesn’t save them on file.

The process above is repeated for all zone files.

After that, you need to reload daemons and restart named.

[[email protected]
named]# systemctl daemon-reload 
[[email protected]
named]# systemctl restart named

Leave a Reply

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