C/Ruby/Perl/bash: How to check for root user


Often, during my work, I must check for the user that is launching my applications, specifically some applications like ping/shutdown/../.. need to be executed by root user.

I collected four pieces of code in four languages 



raise 'Must run as root' unless Process.uid == 0





    printf("You must be root to run this app\n");





if [ "$(id -u)" != "0" ]; then

   echo "This script must be run as root" 1>&2

   exit 1




$login = (getpwuid($>)); if (!$login == "root") { die "\nYou cannot run this Perl script as user \"$login\", must be ROOT!\n\n"; }

As suggested by Renée there was a bug so use the following:

my $login = (getpwuid $>);
die "must run as root" if $login ne 'root';


You may also like...

3 Responses

  1. Your Perl code is buggy:
    you get the login name and then you negate it (!$login). If you negate a string you get “” (empty string).
    Then you use “==” and that forces a numeric context. Strings in numeric context is a bit weird (at least for Perl beginners): If there is a number at the beginning of the string, that number is used ( “34test” => 34, “24test23” => 24). But neither the empty string nor the string “root” has a number at the beginning. So the second rule is taken: Without the number at the start, Perl uses 0 (“root” => 0, “test23” => 0).

    So your comparison is 0 == 0 and that’s always true.

    If you want to compare strings, you have to use
    eq => ‘root’ eq ‘root’ => 1; ‘root’ eq ‘test’ => 0
    ne => ‘root’ ne ‘root’ => 0; ‘root’ ne ‘test’ => 1
    lt, gt, le, ge,…

    In Perl you could use:

    my $login = (getpwuid $>);
    die “must run as root” if $login ne ‘root;

    or simply

    die “must run as root” if $> != 0;

  2. admin says:

    Thak you very much for your post.

  3. Julien says:

    You should have taken the last one-liner for Perl, as it does the same as the snippets in the other languages (ie checking for uid == 0) :)

    This makes it so clear that Perl rules. 😉

Leave a Reply

Your email address will not be published. Required fields are marked *