我正在编写一个 bash 脚本来帮助我更快地设置我的 rpi 的网络接口。它现在已经基本完成,并且使用 sed 来更改 /etc/network/interfaces 文件的不同部分,具体取决于网络接口的设置方式。我的问题是我在不想要引号的地方插入引号,如果我删除引号,我会插入包含要作为变量名字符串插入的数据的变量,而不是将它们作为值插入。
我的代码如下(虽然我已经把它删掉了)
#!/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
}
问题是这里的这些行
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
哪个插入address "(var_address)"
。正如我所说,我可以让它插入address $address
。但不是,如我所愿,address (var_address)
。有人可以解释如何在 sed 命令中使用 / 和 \ 以及 " 和 ' 以便我可以解决问题。正如您可能已经猜到我对 bash 有点陌生,因此感谢您的帮助。