I am trying to set net.ipv4.ip_forward
to 1 in /etc/sysctl.conf
.The following works fine but it sure missing some edge cases
#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
For e.g if the sysctl.conf contain any one of the following it won’t match
#net.ipv4.ip_forward=1
##net.ipv4.ip_forward=1
.
Is there a more reliable way to modify settings in config files ?
Advertisement
Answer
You can use the -r
switch to enable Extended Regular Expressions(ERE
) in GNU sed
and optionally match the white-space and the #
occurence with the regex ?
optional item anchor,
sed -ir 's/#{1,}?net.ipv4.ip_forward ?= ?(0|1)/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf
This will match for any of the below input lines and modify it with the replacement part 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
See the RegEx Demo for more clarity.