Redirect the output using `sudo` [duplicate]

Solution 1:

Your approach with sudo tee is fine. A nice consequence of using sudo tee is that the executed command before the pipe will not run as root. That's useful if you just need the output of a program, which does not require root privileges.

If you don't care about the output of the program used before the pipe (echo 1 in this case), redirect stdout to /dev/null:

echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward > /dev/null

The above is equivalent to sudo sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward' with the difference that echo 1 is run as root.

If you need to append to a privileged file, you can either use sh -c 'echo 127.0.0.1 local.host >> /etc/hosts' or:

echo 127.0.0.1 local.host | sudo tee -a /etc/hosts

Note the -a which is shorthand for --append.

Solution 2:

One solution is to use :

sudo bash -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'

but this one doesn't inherit env properties from the parent shell, so you can't use it for example with echo $PATH to get the same result you'd have in your parent shell (of course only in case you alter your path property) .

Using sudo -E will preserve the environment variables.

Also, according to https://wiki.ubuntu.com/DashAsBinSh, you'd be better off using sh (which is a symlink to dash), instead of invoking this with bash.

So, you might rewrite this as :

sudo -E sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'

Solution 3:

I usually use the sudo bash -c trick, or just do sudo -s first to stay root, then run the redirection command.

The reason it doesn't work the first way is that the shell processes the redirection first, then runs sudo. Since your shell doesn't have access to the file, the redirection fails.