bashshellroot

How to check if running as root in a bash script


I'm writing a script that requires root level permissions, and I want to make it so that if the script is not run as root, it simply echoes "Please run as root." and exits.

Here's some pseudocode for what I'm looking for:

if (whoami != root)
  then echo "Please run as root"

  else (do stuff)
fi

exit

How could I best (cleanly and securely) accomplish this? Thanks!

Ah, just to clarify: the (do stuff) part would involve running commands that in-and-of themselves require root. So running it as a normal user would just come up with an error. This is just meant to cleanly run a script that requires root commands, without using sudo inside the script, I'm just looking for some syntactic sugar.


Solution

  • A few answers have been given, but it appears that the best method is to use is:

    id -u
    

    If run as root, this command will return an id of 0.

    This appears to be more reliable than the other methods, and it seems that it return an id of 0 even if the script is run through sudo.

    Here is an example of checking if running as root in a bash script (using `id -u` inline to do so):

    #/bin/bash
    if [ $(id -u) -ne 0 ]
      then echo Please run this script as root or using sudo!
      exit
    fi
    # Remainder of script goes below this line