…with an open minded approach

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:

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

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.