LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash :: change file value on /sys directory (https://www.linuxquestions.org/questions/programming-9/bash-change-file-value-on-sys-directory-4175411077/)

finaccio 06-12-2012 01:56 PM

bash :: change file value on /sys directory
 
hi!

How I can change the value of a file in /sys virtual filesystem with a script that run regardless the users who is logged.

Thanks a lot for your help

Finaccio

Nominal Animal 06-12-2012 02:42 PM

You use sudo to run the script with elevated access privileges.

A simple way to do that is as follows. First, put the privileged stuff in a separate script, say /usr/local/bin/do-the-sys-stuff:
Code:

#!/bin/bash
[ "`id -u`" = "0" ] || exec sudo -- "$0" "$@"

# do the /sys stuff here

The second line causes the script to rerun itself via sudo if run without root privileges.

Then, allow any user to use sudo to run that script as root without a password, by adding line
Code:

ALL ALL = (root) NOPASSWD: /usr/local/bin/do-the-sys-stuff
into /etc/sudoers.d/allow-do-the-sys-stuff if /etc/sudoers.d/ exists, in /etc/sudoers otherwise. If you create a new file, make sure it is owned by root and has mode 0440: chown 0:0 file && chmod 0440 file

After that, any user can run /usr/local/bin/do-the-sys-stuff as themselves, causing it to rerun itself with root privileges via sudo, and doing your /sys stuff with root privileges.

Questions?

finaccio 06-12-2012 02:46 PM

no questions!!

thanks a lot for your answer!

I am going to try your advices and I will give you feedback asap!

Finaccio

finaccio 06-12-2012 02:51 PM

fantastic! It works!

thanks a lot for your help Nominal Animal

Finaccio

David the H. 06-13-2012 09:14 AM

A small addition, if I may.

As long as we're using bash, we can test the built-in $UID variable instead of running the external id command. (There's also $USER if you want the username string).

You should also take care to use arithmetic operators when doing integer comparisons. That's "-eq" inside the square-bracket tests ("=" is a string comparison). But actually, the ((..)) arithmetic evaluation bracket is the recommended structure to use in bash or ksh, where "==" is used for equality.

http://mywiki.wooledge.org/ArithmeticExpression
http://mywiki.wooledge.org/BashFAQ/031

I prefer using the "&&" logic myself, BTW. It reads more naturally.
Code:

#!/bin/bash
(( UID != 0 )) && exec sudo -- "$0" "$@"

# do the /sys stuff here

Using "(( UID ))" alone would also work here, since "0" evaluates as false, and other values as true.


And don't forget: $(..) is highly recommended over `..`


All times are GMT -5. The time now is 04:57 AM.