I'm trying to write a bash script (in Ubuntu) that will backup a directory using tar.
How can I do a check in the script so that it can only be run as root (or with sudo)?
For instance, if a user runs the script, it should say that this script must be run with sudo privileges, and then quit. If the script is executed as root, it will continue past the check.
I know there has to be an easy solution, I just haven't been able to find it by googling.
To pull the effective uid use this command:
If the result is ‘0’ then the script is either running as root, or using sudo. You can run the check by doing something like:
I assume you know that by changing the ownership to root
chown root:root file
and setting the permissions to 700
chmod 700 file
you will accomplish the same thing - without the suggestion to run as sudo.
But I will post this answer for completeness.
The bash variable
$EUID
shows the effective UID the script is running at, if you want to make sure the script runs as root, check wether$EUID
contains the value 0 or not:This is better than the solution with
/usr/bin/id
(for bash scripts!) because it doesn't require an external command.What is your objective here, to inform the user that they should run the script as root or as some kind of security precaution?
If you just want to inform the user than any of the uid suggestions are fine, but they're as useful as tyres on a horse as a security precaution - there's nothing to stop a user from copying the script, taking out the if statement, and running it anyway.
If this is a security issue then the script should be set to 700, owned by root:root, so that it is not readable or executable by any other user.
You can use whoami command as well.
One simple way to make the script only runnable by root is to start the script with the line:
#!/bin/su root
"#!/bin/su root" allows users in super user mode to run the script without using the root password. If you want super users to run the script with results that of root, this does that.