Take the 2-minute tour ×
Raspberry Pi Stack Exchange is a question and answer site for users and developers of hardware and software for Raspberry Pi. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer

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"

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.