Ubuntu – ‘sudo echo “bla” >> /etc/sysctl.conf’ Permission Denied

amazon ec2sshsudoUbuntu

Disclaimer: I'm pretty novice at sysadmin stuff.

I'm trying to set up port forwarding in an AWS EC2 instance, this has to be done in the command-line because I don't want to go in and edit anything, it has to be automatic (it's part of a build process).

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

Permission denied

The weird thing is I've been (successfully) using sudo for pretty much every command that required su privileges. If I do sudo su before the command (trying it out by hand in an ssh session), then it works.

Reasons behind this? Possible solutions that don't involve sudo su or manual edits?

Best Answer

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"