LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Code to ensure script runner is root user (https://www.linuxquestions.org/questions/linux-newbie-8/code-to-ensure-script-runner-is-root-user-947090/)

mogleyzw 05-27-2012 06:34 AM

Code to ensure script runner is root user
 
Hi,

I just need a code fragment with checks if the user is the root user.

Basically I need to ensure it was run as "sudo myscript" rather then just "myscript"

I found

Code:

if [ "$USER" != "root" ]; then
    echo "You are not root user, please log in as root user"
    exit
fi

But that didn't work. I thought maybe it was because I had not defined the variable $USER and I wasn't sure how to.

Any help will be appreciated.

eSelix 05-27-2012 06:43 AM

You can use "id" program, like that:
Code:

if [ $(id -ur) != 0 ]; then
    echo "You are not root user, please log in as root user"
    exit
fi


sysfce2 05-27-2012 09:21 AM

Why not just set the execute permissions so that only root can run the script?


All times are GMT -5. The time now is 06:44 PM.