`sudo echo "bla" >> /etc/sysctl.conf` permission denied

Solution 1:

You can't use sudo to affect output redirection; > and >> (and, for completeness, <) are effected with the privilege of the calling user, because redirection is done by the calling shell, not the called subprocess.

Either do

cp /etc/sysctl.conf /tmp/
echo "net.ipv4.ip_forward = 1" >> /tmp/sysctl.conf
sudo cp /tmp/sysctl.conf /etc/

or

sudo /bin/su -c "echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf"

Solution 2:

You might find it simpler to use this command:

echo net.ipv4.ip_forward = 1 | sudo tee -a /etc/sysctl.conf

Solution 3:

sudo runs only your command, not the redirect, as root. You'll need to wrap it all in a command where the whole thing runs as root:

sudo sh -c 'echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf'

Solution 4:

The command sudo echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf is interpreted as that you (nonroot) write the result of sudo echo "net.ipv4.ip_forward = 1" into /etc/sysctl.conf.

Run

sudo -s 'echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf'

or

sudo su -c 'echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf'

to run echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf as root.


Solution 5:

sudo sed -i "$ a <text>" <file>
  • -i : edit file in place.
  • $ a: append text to the last line

Using sed command avoids you the hassle of redirections and pipelines.

In your case: sudo sed -i "$ a net.ipv4.ip_forward = 1" /etc/sysctl.conf