How to check if running as root in a bash script

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

    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).

提交回复
热议问题