Reputation: 51
On a raspberry pi I am trying to write a simple script that will allow me to change the static ip settings in the dhcpcd.conf file. The below script works except for the dns-servers. It appears that the sed statement does not work for that line as it contains two ip addresses seperated by a space. The script is as follows:
#!/bin/bash
currip=$(cat /etc/dhcpcd.conf | grep -e '^static ip_address=' | cut -d= -
f2)
currgw=$(cat /etc/dhcpcd.conf | grep -e '^static routers=' | cut -d= -f2)
currdns=$(cat /etc/dhcpcd.conf | grep -e '^static domain_name_servers=' |
cut -d= -f2)
echo "current IP is $currip"
echo "current GW is $currgw"
echo "current DNS servers are $currdns"
echo "Enter new static ip in form of x.x.x.x/x: "
read newip
echo "Enter new GW in form of x.x.x.x: "
read newgw
echo "Enter new DNS servers in form of x.x.x.x x.x.x.x: "
read newdns
echo "currip is $currip"
echo "new ip will be $newip"
echo "new dns will be $newdns"
sed -i -e "s@$currip\b@$newip@g" /etc/dhcpcd.conf
sed -i -e "s@$currgw\b@$newgw@g" /etc/dhcpcd.conf
sed -i -e "s@$currdns\b@$newdns@g" /etc/dhcpcd.conf
chip=$(cat /etc/dhcpcd.conf | grep -e '^static ip_address=' | cut -d= -
f2)
chgw=$(cat /etc/dhcpcd.conf | grep -e '^static routers=' | cut -d= -f2)
chdns=$(cat /etc/dhcpcd.conf | grep -e '^static domain_name_servers=' |
cut -d= -f2)
echo "The ip has been changed to $chip"
echo "The GW has been changed to $chgw"
echo "The DNS server have been changed to $chdns"
The lines in the dhcpcd.conf file look like this:
static ip_address=192.168.126.7/24
static routers=192.168.126.1
static domain_name_servers=192.168.126.1 66.243.243.101
How do I need to tweak my sed statement for the domain_name_servers?
Upvotes: 1
Views: 1995
Reputation: 363
The problem is your static router "192.168.126.1" is also present in the static domain_name_servers. Therefore, when you overwrite the routers with
sed -i -e "s@$currgw\b@$newgw@g" /etc/dhcpcd.conf
the line in your conf file is changed to
static domain_name_servers={{what you entered}} 66.243.243.101
so it no longer it matched by the name servers sed.
I suggest changing the find and replace strings to include the keys as well as the values, such as in the following:
sed -i -e "s@^static ip_address=$currip\b@static ip_address=$newip@g" dhcpcd.conf
sed -i -e "s@^static routers=$currgw\b@static routers=$newgw@g" dhcpcd.conf
sed -i -e "s@^static domain_name_servers=$currdns\b@static domain_name_servers=$newdns@g" dhcpcd.conf**strong text**
This will make it so no other lines that happen to contain an earlier replaced-string will be changed
Upvotes: 1