using tee to echo to a system file with sudo privileges

It is always a good practice not to execute privileged by logging as root. We can avoid
that by executing with sudo privileges. Many times , we need to change kernel parameter
for changing the behaviour of a Linux system . Like recently there was a need for me to
change the CPU governor from 'userspace' to 'ondemand' on a Linux system.

I have to use the following command to complete the task .

$ sudo echo userspace > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

We have to execute the command as priviliged user , so I was trying to do it using sudo . But it was failing with the following error. But if I do by logging with uid=0 , then it succeeds . But I want to su - to root.

$ sudo echo ondemand > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
-bash: /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor: Permission denied

This was because the above command has two parts and we are using sudo on the first part (sudo echo userspace) , which itself does not need sudo as we are just echoing. In the second part , we are writing to a system file ( > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ) as a normal user
which will not be allowed.
tee is the command which can help us to execute the above command without logging as root. As per man page, tee read from standard input and writes to standard output and files.


$ echo ondemand | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
ondemand

$ sudo cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
ondemand

So, in the above command , tee is reading from pipe and write to the system file with sudo . Using cat , I verified the value of the system file and I could see the value changed from userspace to ondemand.
That's it , we are done.





 

Comments

Popular Posts