0

i am trying to write a script that will edit a config file on ubuntu

i need to enable an option for ip forward for the file /etc/sysctl.conf

i need to edit this line, from this

#net.ipv4.ip_forward = 0

to that:

net.ipv4.ip_forward = 0

to remove the "#"

can i do it with a script?

thanks for the help!

2
  • 1
    Try sed -i 's/^#\(net.ipv4.ip_forward.*\)/\1/' /etc/sysctl.conf. Try it without the -i first to see if it works as expected.
    – doneal24
    Commented Jul 25, 2022 at 18:49
  • Please be aware that your code requirement does not match your written requirement. The code as shown will enable the setting that disables forwarding for IPv4. I think you also meant to change the line to net.ipv4.ip_forward = 1. Commented Jul 25, 2022 at 19:12

1 Answer 1

0

You should use the Stream EDitor sed to do this.

sudo sed -i '/net\.ipv4\.ip_forward =/s/^#//' /etc/sysctl.conf

This command runs using sudo, which is needed to edit /etc/sysctl.conf. sudo calls sed -i which edits the files instead of printing the result to stdout. /net\.ipv4\.ip_forward =/ is a regex that looks for lines to modify, and s/^#// removes # only if it is the first character of the line.

One good practice when finding the right syntax for your edits is to not use sed -i and instead just use sed and view what comes out.

Also, if you want another safety net, you can run sed -i.bak which will create a backup file with .bak as the suffix. Be careful where you use that though, because the backup is created in the same dir as the original file, which can cause issues in various circumstances, such as when all the files in a directory are read, such as various .d directories.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .