Tired of su-ing
One axiom of computing is to script commonly-used command sequences, akin to C’s functions, Pascal’s procedures, and Ada’s subprograms. But what if the command sequence involves “su” for elevated privileges? I found an idiom that Works For Me.
This example will pull pages from the swap space back into RAM:
#!/bin/sh case `id -u` in # The task is accomplished in the 0 case, # where we know we have root privileges. 0) /sbin/swapoff -a /sbin/swapon -a ;; # Everyone else gets to provide a password: *) exec /bin/su -c "`which $0`" - ;; esac
Anything requiring elevated privileges, or even simply someone else’s privileges, can be scripted this way. I have the above script in ~/bin/unswap. I have three other scripts in the same directory, called “slow”, “normal”, and “fast”, which set the CPU frequency governor to powersave, ondemand, or performance.
The one caveat is to hard-code the paths to the root-executed programs (which you already do in scripts, right?). You don’t want to execute a non-standard “swapon” that isn’t where you expect it to be.
(If someone would like to contribute an example using “sudo” instead of “su” it would be greatly appreciated.)