Change DNS server by editing /etc/resolv.conf file (using sed) and problem
Solution 1
The way >
redirection operates, the output file is truncated before any of the commands are run, which means the cat
ought 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 run sed -e '...' resolv.conf~ > resolv.conf
, no need for cat
). Alternatively, if you have GNU sed you can use the in-place editing option (sed -i
), again no need for cat
.
Solution 2
use this code (untested):
sed 's/nameserver.*/nameserver 192.168.1.5/' /etc/resolf.conf > /etc/resolf.conf.new
mv /etc/resolf.conf.new /etc/resolf.conf
sees
Updated on June 04, 2022Comments
-
sees almost 2 years
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.5but 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?