The other day I wanted to enable IP forwarding on my Linux box (so that it could forward packets from a tun virtual interface being used by VTun to the physical interface connected to my home network).
I looked up it up and it turns out that it’s a simple setting in a file in the /proc
filesystem, so I did what seemed obvious and logical at the time:
marca:~$ sudo echo "1" > /proc/sys/net/ipv4/ip_forward -bash: /proc/sys/net/ipv4/ip_forward: Permission denied
I took this to mean that my kernel was not compiled with ip_forward support and then wasted a bunch of time building a new kernel.
Finally, it dawned on me. Duh. The echo
command is a shell built-in so sudo has no effect.
I didn’t need a new kernel. All I had to do was:
marc:~$ sudo bash root:~# sudo echo "1" > /proc/sys/net/ipv4/ip_forward root:~# cat /proc/sys/net/ipv4/ip_forward 1
or even:
marc:~$ sudo sh -c 'echo "1" > /proc/sys/net/ipv4/ip_forward'
Sigh.
I thought of the idea of preventing this in the future by defining a bash function that detects builtins:
function sudo() { if [ $(type -t "$1") == "builtin" ]; then echo "sudo bash function: ERROR - \"$1\" is a shell builtin" 1>&2 return 1 fi command sudo "$@" }
which works for some cases but unfortunately doesn’t help for the case above, because the redirection permissions are checked before the function is executed. Sigh.
I think the problem is not that echo is a shell builtin but rather that the file you’re trying to redirect to is being opend by the shell before the sudo is executed and therefore the command fails because user “marc” doesn’t have write permissions on the file.
sudo /bin/echo 1 > /root/test
doesn’t work either while
sudo sh -c “/bin/echo 1 > /root/test”
does as you have already noted.
Good work man..it really helped
the problem in this is not of builtin as echo is also a program
$which echo
/bin/echo
but doing something like fails as ‘cd’ is only a builtin
$sudo cd /root
sudo: cd: command not found
Your post really helped me. Thanks!
thanks a lot
but I still mazing about it?why shell-builtin cmd can not work with sudo?Is there any else?