LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to check if i'm root in a script? (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-check-if-im-root-in-a-script-490390/)

Maverick1182 10-07-2006 01:43 PM

How to check if i'm root in a script?
 
Hi there i wanted to make it easier for me to install things by making a script of repetitive or long commands. I was just wondering if there is a way of checking if i'm root. If i am logged in as root then to continue to the next commands and if i'm not then to stop and warn me? I was thinking of something like passing the output of "whoami" to a variable but I dont know how to do this. Is there a more elegant way to do this? or is there a command already out there which does this?

Any help would be appreciated.

extrasolar 10-07-2006 01:46 PM

Well, if the file is owned by root then can't you just chmod the file so that only the owner of the file can execute it?

Or am I missing something?

RedNovember 10-07-2006 02:12 PM

Hell, you could, say, do something like:
Code:

whoami > /home/username/whoami
cat whoami > (something)

Then again, you'd still need this variable idea from there, so some command could use it as an argument.

zetabill 10-07-2006 02:21 PM

Code:

[ $(whoami) == "root" ]
will return 1 (yes) if you are logged in as root and 0 (no) if you are not. The spaces after the open bracket and before the close bracket are necessary because it is actually an alternate of the test statement. If you want to learn more about test (and its alternate [ ]) you can `man test`.
Code:

if [ $(whoami) == "root" ]; then
    execute root commands
else
    warn user
fi

It's a rudimentary implementation but that'll get the job done. I would also consider extrasolar's comment that if it's important that only root execute something then it should be owned and executed by root exclusively. In which case you could chown root.root and chmod 744 the file. I have some that are 700 only but I'm anal with that stuff.

A good compromise if you want to have a script for a user with optional root commands, you could use that if statement and instead of warning a user that you aren't root then you could actually make a separate script with the root commands and call it from that script with `su -c "rootscript"` that way it would ask for a password. It seems crude but it'll work. There are certainly better solutions but I'm not an expert.

Good luck!

Maverick1182 10-07-2006 05:20 PM

Great, just what i was after, thanks for the prompt help guys/gals. Much appreciated!


All times are GMT -5. The time now is 07:48 AM.