Ubuntu – Redirect the output using `sudo`

command linesudo

I have a small question regarding using sudo with output redirect >. To enable IP forwrding, someone can use the command:

echo 1 > /proc/sys/net/ipv4/ip_forward

Executing this command will give permission denied as it requires root privileges. However, executing the same command with sudo gives also permission denied error! It seems that output redirect > does not inherit the permissions of the preceding command echo. Is this right?

As a workaround I do:

echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward

Is this the best way to do it? Am I missing something?

Please, note that this is an example and it applies to all commands that use output redirect.

Best Answer

  • 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.

  • Related Question