Im writing a bash script to help me set up my rpi’s network interfaces faster. It is mostly finished now and works using sed to alter different parts of the /etc/network/interfaces files depending how the network interface is being set up. My problem is that i am inserting quotation marks where i don’t want them and if i remove the quotation marks i insert the variables containing the data to be inserted as a string of the variable name as oppose to inserting them as their value.
My code is as followed (although i have cut it down)
#!/bin/bash
ANS=''
ssid=''
psk=''
file='/etc/network/interfaces'
ip=''
netmask=''
broadcast=''
gateway=''
function static {
echo 'Will now set up Static IP'
echo 'What IP address do you want to assign this Device?'
echo -e '> \c'
read ip
echo 'What is your Networks Netmask/Subnet?'
echo -e '> \c'
read netmask
echo 'What is your Networks Broadcast Address?'
echo -e '> \c'
read broadcast
echo 'What is the address of your Networks Gateway?'
echo -e '> \c'
read gateway
echo 'You entered the following information about your Network'
echo ''
echo 'Address: ' $ip
echo 'Netmask: ' $netmask
echo 'Broadcast: ' $broadcast
echo 'Gateway: ' $gateway
echo 'Is this information correct? (y/n)'
echo -e '> \c'
read ANS
if [ $ANS = 'y' ]; then
sed -i "s/^iface eth0 inet dhcp.*\$/iface eth0 inet static/" $file
sed -i "s/^# address.*\$/ address \"$ip\"/" $file
sed -i "s/^# netmask.*\$/ netmask \"$netmask\"/" $file
sed -i "s/^# broadcast.*\$/ broadcast \"$broadcast\"/" $file
sed -i "s/^# gateway.*\$/ gateway \"$gateway\"/" $file
echo 'Static IP address has now been set up'
start
else
static
fi
}
The problem is these lines here
sed -i "s/^# address.*\$/ address \"$ip\"/" $file
sed -i "s/^# netmask.*\$/ netmask \"$netmask\"/" $file
sed -i "s/^# broadcast.*\$/ broadcast \"$broadcast\"/" $file
sed -i "s/^# gateway.*\$/ gateway \"$gateway\"/" $file
which insert address "(var_address)". As i said i can get it to insert address $address. But not, as i want, address (var_address). Could someone please explain how to use the / and \ together with ” and ‘ in the sed command so that i can fix the problem. As you may have guessed im a bit of a newb to bash so any help is appreciated.
While bash won’t try to resolv no standard variables, like
$/, you could simply:Nota: This modify only 1 paragraph concerning
$iface: with the first sed line:/^iface $iface/,/^$/{ ... }delimit a command block who could be executed only from a line matching/^iface $iface/to an empty line (or end of file).And for playing with IP address in bash, take a look at https://serverfault.com/a/461831/142978