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?

2 Answers 2

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.

1
  • How do you disable this again? Commented Dec 2, 2018 at 11:30
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" 
1
  • The answer above works on the pi zero: response = os.system("sudo sh -c \"echo {} >/sys/class/leds/led0/brightness\"".format(led_to)) Commented Apr 28, 2021 at 23:29

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.