Sometimes sudo seems to not work
Sudo is a program that is often used to gain root access in a safer way than logging in as root user. In some situations, however, using sudo may fail, requiring root login to perform the operation. This article describes one of such situations and a workaround that requires no root login.
As an example, I will use
echo 1 > /sys/class/leds/input2::capslock/brightness command. Running this command should light up "Caps Lock" indicator on the keyboard. Trying to run this command with sudo fails with
Permission denied message, while running it from root shell works fine.
Why does this happen?
sudo echo "1" > /sys/class/leds/input2::capslock/brightness does not actually allow to write to that file with root permission, as this command contains output redirection (
>), that is performed by command line shell running as user, rather than by
echo command that is running as root.
In order to run a command like this without root login writing to the file with root access is required. One way to accomplish this is running just a single command as root using
sudo bash -c "echo 1 > /sys/class/leds/input2::capslock/brightness". This will run the command with a root shell and return the operation to normal user shell.
Another way to do this is piping the output of echo into some command that will write to the file with root access, such as
echo 1 | sudo tee /sys/class/leds/input2::capslock/brightness
Available as video here