6

I was playing with the raspberry pi leds (How do I control the system LEDs using my software?)

Interestingly, on my pi the following command fails:

sudo echo heartbeat >/sys/class/leds/led0/trigger

The error is bash: /sys/class/leds/led0/trigger: Permission denied

However if I run the following pair of commands things work:

sudo -s
echo heartbeat >/sys/class/leds/led0/trigger

I would have thought the two ways of triggering the LEDs are the same. Are there some things sudo cannot do?

John Smith
  • 1,251
  • 3
  • 17
  • 27

2 Answers2

10

The shell interprets and handles redirection before the command is executed. So the redirection (>/sys/class/leds/led0/trigger) is attempted with the user's permissions, thus fails.

The generally recognized solution is to use the tee command: (man page and wikipedia)

echo heartbeat | sudo tee /sys/class/leds/led0/trigger >/dev/null

The tee command splits (tees!) its input into two streams, one going to a file specified on the command line, the other to stdout. In this example, I've used the ability to specify a filename to write to that file with sudo privileges, and discard the duplicate output going to stdout.

lornix
  • 1,066
  • 8
  • 13
6

As explained by lornix it's because the shell handles redirection before the command is executed.

I prefer this type of invocation

sudo sh -c "echo 4 >/sys/class/gpio/export"

In your case

sudo echo heartbeat >/sys/class/leds/led0/trigger

would become

sudo sh -c "echo heartbeat >/sys/class/leds/led0/trigger"
joan
  • 71,024
  • 5
  • 73
  • 106
  • The answer above works on the pi zero: response = os.system("sudo sh -c "echo {} >/sys/class/leds/led0/brightness"".format(led_to)) – pierre Apr 28 '21 at 23:29