I am working a script to generate a config file that I want to store in /etc/solignis. When I run the script as a limited user it does not allow me to create the directory or write the file. So the script will have to run as sudo or a root user, how can I check if the user is a root or atleast using sudo?
Asked
Active
Viewed 1.4k times
14
-
8Why would you check if the user is root? Just try to create the directory, check if it fails, and then report a message on failure. In other words, the best way to check if you have the correct privileges to do something is to try and do it. – William Pursell Mar 12 '11 at 04:19
-
Kind of lame, but about about `(getlogin() || getpwuid($<)) eq 'root'`? – Hugmeir Mar 12 '11 at 04:20
-
@William Pursell is the best option, simply try it and see. Nowadays as the rights systems get more sophisticated, even "root" may well not be root anymore. Since you're going to write it anyway, just try it and fail rather than making some presumption of power based on the user name or uid. – Will Hartung Mar 12 '11 at 04:28
4 Answers
30
If $>
(aka $EFFECTIVE_USER_ID
if you use English
) is non-zero, then the user is not root.

cjm
- 61,471
- 9
- 126
- 175
-
William Pursell's solution would be even better, though - the user just may well have had root give the necessary privileges to do the task. – Arafangion Mar 12 '11 at 04:23
-
Ok so 0 is the uid for root or is that the gid?, For a second it did think it would then I realized I made a coding error, it works – AtomicPorkchop Mar 12 '11 at 04:30
-
2This answers the poster's question, but the poster is asking the wrong question and has ended up with a non-solution. Open the file. If it fails, report the attempted operation, full pathname and the system error message ($!). There is nothing ambiguous about "Permission denied," which could possibly occur even when the user is root. – converter42 Mar 12 '11 at 21:46
4
XAppSoftware: How to check for root user has a solution:
my $login = (getpwuid $>);
die "must run as root" if $login ne 'root';

Sonia Hamilton
- 4,229
- 5
- 35
- 50
1
I had the same question and ended up using the results of all three previous answers:
die "Must run as root\n" if $> != 0;

jtylers
- 11
- 2
0
if ( $< != 0 ) {
print "This script must be run as root\n";
exit (0);
}
-
Note that $< will use the userid you are coming from. Therefore, if you do sudo then this will check against the original user but not root. If you want to check against the userid you are going to then use $> (as answered by cjm above). Also for those who want to use die and unless instead you can use: die "This script must be run as root\n" unless $< == 0; – armannvg Nov 01 '13 at 16:27