How to check if running as root in a bash script

前端 未结 17 771
太阳男子
太阳男子 2020-12-04 04:44

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 exit

17条回答
  •  青春惊慌失措
    2020-12-04 05:25

    In a bash script, you have several ways to check if the running user is root.

    As a warning, do not check if a user is root by using the root username. Nothing guarantees that the user with ID 0 is called root. It's a very strong convention that is broadly followed but anybody could rename the superuser another name.

    I think the best way when using bash is to use $EUID, from the man page:

    EUID   Expands to the effective user ID of the current  user,  initialized
           at shell startup.  This variable is readonly.
    

    This is a better way than $UID which could be changed and not reflect the real user running the script.

    if (( $EUID != 0 )); then
        echo "Please run as root"
        exit
    fi
    

    A way I approach that kind of problem is by injecting sudo in my commands when not run as root. Here is an example:

    SUDO=''
    if (( $EUID != 0 )); then
        SUDO='sudo'
    fi
    $SUDO a_command
    

    This ways my command is run by root when using the superuser or by sudo when run by a regular user.

    If your script is always to be run by root, simply set the rights accordingly (0500).

提交回复
热议问题