我想在net.ipv4.ip_forward
中将/etc/sysctl.conf
设置为1.以下工作正常,但肯定会遗漏一些边缘情况
#Enable IP packet forwarding so that our VPN traffic can pass through.
sed -i 's/net.ipv4.ip_forward = 0/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf
sed -i 's/#net.ipv4.ip_forward = 1/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf
grep -qF "net.ipv4.ip_forward" /etc/sysctl.conf || echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
例如,如果sysctl.conf包含以下任何一项,则不匹配
#net.ipv4.ip_forward=1
##net.ipv4.ip_forward=1
。
是否有更可靠的方法来修改配置文件中的设置?
答案 0 :(得分:4)
您可以使用-r
开关在ERE
中启用扩展正则表达式(GNU sed
),并可选择将空格和#
与{sed -ir 's/#{1,}?net.ipv4.ip_forward ?= ?(0|1)/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf
匹配3}},
net.ipv4.ip_forward = 1
这将匹配以下任何输入行,并使用替换部分net.ipv4.ip_forward=0
net.ipv4.ip_forward = 0
#net.ipv4.ip_forward=0
##net.ipv4.ip_forward = 0
#net.ipv4.ip_forward=1
##net.ipv4.ip_forward=1
#net.ipv4.ip_forward = 1
##net.ipv4.ip_forward = 1
{{1}}
有关更清晰的信息,请参阅regex ?
optional item anchor。
答案 1 :(得分:1)
如果删除与net.ipv4.ip_forward
匹配的所有行,无论是否已注释掉,然后附加您需要的内容,该怎么办?
fgrep -v net.ipv4.ip_forward /etc/sysctl.conf > /etc/sysctl.conf.tmp
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf.tmp
mv /etc/sysctl.conf.tmp /etc/sysctl.conf
这很简单易读。
答案 2 :(得分:0)
您可以使用此设置为零个或多个空格以及零个或多个#(注释)
执行此操作sed -i 's/[#| ]*net.ipv4.ip_forward[ ]*=[ ]*0/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf
grep -qF "net.ipv4.ip_forward" /etc/sysctl.conf || echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf