I want to change the DNS server for my Linux machine. So, I’m going to edit /etc/resolv.conf file.
The command I’m using is SED. And doing as below for change DNS server to 192.168.1.5:
#cat /etc/resolv.conf | sed '/nameserver/ c\ nameserver 192.168.1.5' > /etc/resolv.conf
The problem is:
When I execute the command the first time and it changes the resolv.conf to something like:
domain somedomain
namserver 192.168.1.5
but when I execute it once again to change DNS server to 192.168.1.4:
#cat /etc/resolv.conf | sed '/nameserver/ c\ nameserver 192.168.1.4' > /etc/resolv.conf
The file resolv.conf becomes empty
Questions:
1. Am I doing the right way to change DNS server?
2. Is there problem with the sed command in the above command?
The way
>redirection operates, the output file is truncated before any of the commands are run, which means thecatought to see an empty file so the expected result is nothing. I am a bit puzzled as to why your first invocation works. You should use a temporary file (e.g.mv resolv.conf resolv.conf~and runsed -e '...' resolv.conf~ > resolv.conf, no need forcat). Alternatively, if you have GNU sed you can use the in-place editing option (sed -i), again no need forcat.