How to check if running as root in a bash script

前端 未结 17 755
太阳男子
太阳男子 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题