How to check if running as root in a bash script

前端 未结 17 743
太阳男子
太阳男子 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:17
    if [[ $(id -u) -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
    

    or

    if [[ `id -u` -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
    

    :)

    0 讨论(0)
  • 2020-12-04 05:18

    Check for root:

    ROOT_UID=0   # Root has $UID 0.
    
    if [ "$UID" -eq "$ROOT_UID" ]
    then
      echo "You are root."
    else
      echo "You are just an ordinary user."
    fi
    
    exit 0
    

    Tested and running in root.

    0 讨论(0)
  • 2020-12-04 05:19

    As @wrikken mentioned in his comments, id -u is a much better check for root.

    In addition, with proper use of sudo, you could have the script check and see if it is running as root. If not, have it recall itself via sudo and then run with root permissions.

    Depending on what the script does, another option may be to set up a sudo entry for whatever specialized commands the script may need.

    0 讨论(0)
  • 2020-12-04 05:22

    The $EUID environment variable holds the current user's UID. Root's UID is 0. Use something like this in your script:

    if [ "$EUID" -ne 0 ]
      then echo "Please run as root"
      exit
    fi
    

    Note: If you get 2: [: Illegal number: check if you have #!/bin/sh at the top and change it to #!/bin/bash.

    0 讨论(0)
  • 2020-12-04 05:24

    One simple way to make the script only runnable by root is to start the script with the line:

    #!/bin/su root

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题