LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   detecting root user in a bash script (https://www.linuxquestions.org/questions/programming-9/detecting-root-user-in-a-bash-script-687221/)

radiodee1 11-30-2008 06:06 AM

detecting root user in a bash script
 
I'm writing a simple bash script and I want the script to be able to detect weather or not the user running the script is the root user or not. Does anybody know how to do this? Also, can it be done in a way that's not dependent on which distribution you're running? Thanks.

druuna 11-30-2008 06:12 AM

Hi,

Code:

if [[ $UID -ne 0 ]]
then
  echo "$0 must be run as root"
  exit 1
fi

UID is a variable that is set by the shell and holds the uid of the user that started the shell/script. 0 (zero) is (always) the root user.

The above code snippet checks to see if the user is root, if not it prints a message and exits.

Hope this helps.

David the H. 11-30-2008 06:18 AM

The LinuxCommand tutorial gives an example of exactly what you're looking for.

Code:

if [ $(id -u) = "0" ]; then
    echo "superuser"
fi



All times are GMT -5. The time now is 05:53 AM.