Posted 2011/03/31
Sudo and shell redirection
One of our students was stuck using sudo to change a file. This spawned a lengthy email discussion on how the shell works and what sudo actually does.
Here is the crux of the problem:
This works: $ sudo touch /etc/aaaa This does not: $ sudo echo ondemand > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governer
And here is my response:
The shell redirection takes precedence and runs first as you. As you have seen this is all done by root: $ sudo touch /etc/aaaa But this does not work: $ sudo echo ondemand > scaling_governer The reason is because the shell is doing this: as root (echo ondemand) as the user (> scaling_governer) Try this: $ sudo sh -c 'echo "1" > hi'
The 'sudo sh -c' recipe can be used any time you want to use sudo and shell redirection. Another way if things are confusing is to write a shell script and execute the script using sudo.