Sudo Non-Password access to /sys/power/state
Note that the redirection characters "separate" execution and privileges. On this command:
sudo echo disk > /sys/power/state
What you're doing is running echo disk
as root (pointless) and then piping that, as your normal user, into a file that's owned by root, that's why you get permission denied.
This is a very common use case, what you need to do is sudo the part that actually writes to the file instead, something like this works:
echo disk | sudo tee /sys/power/state
You can also create a shell script (a file) with:
echo disk > /sys/power/state
Name it, for instance, script.sh, then run chmod 755 script.sh
and run that with sudo:
sudo /wherever/you/put/this/script.sh
As for running a command without needing a password, that's been discussed before: How do I sudo without having to enter my password?. It can be somewhat insecure; you can control which user gets to execute which command as root without password, but in this case you'd need to allow execution of the tee
command which could allow malicious users to overwrite any file as root. So use with caution and please read all the documentation and understand the security implications of doing this.
Related videos on Youtube
codesmith
Updated on September 18, 2022Comments
-
codesmith over 1 year
On my computer, pm-hibernate appears to be broken, however using the command
echo disk > /sys/power/state
appears to work perfectly. Now I just need regular user access to it, using sudo. How do I do this?The command
sudo echo disk > /sys/power/state
simply returnsbash: /sys/power/state: Permission denied
.Also, I need this in a regularly used script, how can I make it so that I don't have to type in my password for it to work???
-
codesmith over 11 yearsYou learn something new every day, I thought sudo included the entire command. I do have a question though, why did you use '|' over '>' and what does "tee" mean???
-
BlitZz over 11 years
>
directs output to a file.|
directs output to the standard input of another command.tee
is a very simple command that takes its input and outputs it to both standard output and to a file. wiki.bash-hackers.org/howto/redirection_tutorial -
codesmith over 11 yearsOk, thanks for the answer. I've never used either, so I was unfamiliar with both, and before I use any command I like to figure out exactly what it does first.