bash - Check If a script is executed as root?

06
2014-04
  • The KingMaker

    I have a script that requires root privileges. I have to execute it either via sudo or from an account with uid 0 (e.g. root).

    If the script is not executed with sufficient rights then I want that script to echo "Run as Root" and exit 1.

    How can I achieve this ?

  • Answers
  • Hennes
    #!/usr/bin/env bash
    if [[ $EUID -ne 0 ]]; then
       echo "This script must be run as root" 
       exit 1
    fi
    
    // Rest of the script here
    

    Source.

    EUID is the effecvtive UID the script is running as.

    [[ ne ]] is a test on not equal.

    0 is the uid of root (or rather, the uid you want. The name root is the most often name but that can be changed and there can be multiple accounts with uid 0

  • konqui

    You could also make the script just executable by root.

    chmod 700 script (just the file owner can run the script)

    chown root:wheel script (set file owner to root)


  • Related Question

    linux - How can I pass Root Password to a script
  • Questioner

    I have the root password in one of my scripts and I want to launch another script which requires root permission from this script. How can I use the root password which I have so that I do not have to ask the user the root password which launching 2nd script.


  • Related Answers
  • jtimberman

    There's a lot of security implications in this, but let's get right to the best way to handle this.

    Don't use the root password directly. Use sudo to run the scripts. Sudo is installed by default on Ubuntu and is available on almost all popular Linux distributions in the package repositories. Once sudo is installed, you'll want to edit /etc/sudoers.

    su -
    visudo
    # add something like the following:
    Cmnd_Alias SCRIPT=/path/to/script1
    script_user ALL=NOPASSWD: SCRIPT
    

    Thus script_user can run the first script as root through sudo, which would then launch the other script as root. For more information about the sudoers file, see the sudoers(5) man page on your system.

    But do your scripts absolutely have to run as root? Most times this isn't required at all, but is done out of convenience.

  • Simon Sheehan

    Another option would be to set suid on the file to root. Example: chmod u+s script.sh as root so when a normal user executes the script it runs with the file permissions of the owner aka root.

    Just for your own knowledge if you don't want to set sudo to run without a password you can pass the password to sudo through stndin like echo PASSWORD|sudo -S ./script.sh

    However this can be a security concern as it will show the password in history or anyone watching like "ps". You can also look into Expect and Empty.