How to check if running as root in a bash script

前端 未结 17 745
太阳男子
太阳男子 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:34

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

    • id -u
    • If run as root, 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.

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

    There is a simple check for a user being root.

    The [[ stuff ]] syntax is the standard way of running a check in bash.

    error() {
      printf '\E[31m'; echo "$@"; printf '\E[0m'
    }
    
    if [[ $EUID -eq 0 ]]; then
        error "Do not run this as the root user"
        exit 1
    fi
    

    This also assumes that you want to exit with a 1 if you fail. The error function is some flair that sets output text to red (not needed, but pretty classy if you ask me).

    0 讨论(0)
  • If the script really requires root access then its file permissions should reflect that. Having a root script executable by non-root users would be a red flag. I encourage you not to control access with an if check.

    chown root:root script.sh
    chmod u=rwx,go=r script.sh
    
    0 讨论(0)
  • 2020-12-04 05:43

    id -u is much better than whoami, since some systems like android may not provide the word root.

    Example:

    # whoami
    whoami
    whoami: unknown uid 0
    
    0 讨论(0)
  • 2020-12-04 05:43
    #!/bin/bash
    
    # GNU bash, version 4.3.46
    # Determine if the user executing this script is the root user or not
    
    # Display the UID
    echo "Your UID is ${UID}"
    
    if [ "${UID}" -eq 0 ]
    then
        echo "You are root"
    else
        echo "You are not root user"
    fi
    

    Editor's note: If you don't need double brackets, use single ones for code portability.

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