6

I can not run following command with sudo to change a sysfs paramete:

$ sudo echo 300 > /sys/block/md0/md/stripe_cache_size
bash: /sys/block/md0/md/stripe_cache_size: Permission denied

However, it works with out sudo when I change to the root user:

$ sudo su
[root] [ /home/arh ]  
 #  echo 300 > /sys/block/md0/md/stripe_cache_size
[root] [ /home/arh ]  
 # cat /sys/block/md0/md/stripe_cache_size
300

Here is the file permissions:

$ ls -l  /sys/block/md0/md/stripe_cache_size 
-rw-r--r-- 1 root root 4096 Feb  2 08:50 /sys/block/md0/md/stripe_cache_size

Does it make sense to you ?

Note that I have changes /etc/sudoers file with visudo to make sudo commands password-less.

ARH
  • 277
  • 1
  • 3
  • 7

2 Answers2

7

The "echo 300" is executed using sudo, which outputs 300 to stdout in the normal way. Then as your normal user, you are trying to take that output and write to /sys/

Sudo isn't a magic command that elevates privileges for your whole command line. It takes the arguments you passed to it and executes them as a program. Bash (which is running as a normal user) executes 'sudo echo 300' then takes that output and tries to write it to a file. Note that the writing to the file is done by bash which is running as the normal user.

This should work:

sudo bash -c "echo 300 > /sys/block/md0/md/stripe_cache_size"

sudo will execute bash with higher privileges, and then that root bash will execute the whole command.

WillW
  • 186
  • 4
  • In fact, Bash forks, then opens the file and hands over control to whatever command it has been told to execute. Almost same result though, but with the little difference, that the command is never run if it fails to open the output file. – Bachsau Jun 23 '21 at 19:32
6

You run here only echo with sudo command, but - his input/output/stderr are from regular user.

If you wish to write to file as root user, you can't use > from shell. Instead use for example tee command:

echo 300 |sudo tee /sys/block/md0/md/stripe_cache_size
undefine
  • 478