Bash: root-only scripts
Before I forget again, I leave it here
Sometimes you want a script to exit if it’s not run by root.
In those cases, just put a line of code like the one below in the start of the script, so that it exits if the user running is not root:
#exit if user is not root
[ "$(id -u)" != "0" ] && { echo "Must be run as root! Aborting"; exit 1;}
However notice that:
a) there must be a space after the first curly-brace { (between { and echo) or it will not work
b) the last command inside the {} must have ; at the end
Upd 20120602:
Fixed a bug in the script – the command at the right of && should not be enclosed in parenthesis (), it should be enclosed in curly-braces {}
This is because commands inside () will be executed in a subshell (and so the exit 1 will only exit the subshell and not from the script), while commands enclosed in {} will be executed in the current shell
See the clarification here: http://www.gnu.org/software/bash/manual/bashref.html#Command-Grouping