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.
Your approach with
sudo tee
is fine. A nice consequence of usingsudo 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
:The above is equivalent to
sudo sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'
with the difference thatecho 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:Note the
-a
which is shorthand for--append
.One solution is to use :
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 todash
), instead of invoking this withbash
.So, you might rewrite this as :
I usually use the
sudo bash -c
trick, or just dosudo -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.