Linux – How to append new DNS server via command line

bashlinuxmac-osx

I'm trying to write a bash script for OS X that will change will add a nameserver for the current connection. I've got the command to change the DNS servers but I need to preserve the current namesever.

What I thought is that I could get the current nameserver out of the resolv.conf file and then use this somehow in the command.

I've currently got this to change the nameserver to 8.8.8.8:

networksetup -setdnsservers AirPort 8.8.8.8

What I need to do is detect the current nameserver from /etc/resolv.conf and then use the value as a param in the above command. For example say my current resolv.conf looks like this:

nameserver 9.9.9.9

I want the above to command to do this:

networksetup -setdnsservers AirPort 9.9.9.9, 8.8.8.8

Is there a way to use regular expression to extract the IP from resolv.conf and then somehow use this as an argument in the networksetup command?

Best Answer

Minimally tested; for best results, in each [ ], add a tab inside the brackets:

networksetup -setdnsservers AirPort $(sed -ne 's/^[ ]*nameserver[ ]\+\([.:0-9A-Fa-f]\+\)/\1/p' /etc/resolv.conf)

The sed expression extracts addresses from lines that start with the word nameserver followed by an IPv4 or IPv6 address. The $() construct interpolates the output of sed onto the command line of networksetup.

If there's a chance that there won't be any nameserver line in /etc/resolv.conf, here's a relatively simple way:

nameservers=$(sed -ne 's/^[ ]*nameserver[ ]\+\([.:0-9A-Fa-f]\+\)/\1/p' /etc/resolv.conf)
if [ -z "$nameservers" ]; then nameservers=empty; fi
networksetup -setdnsservers AirPort $nameservers