Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have written a bash script for use on my ubuntu box. Now I would like to prevent running this script under my own user and only able to run it as root (sudo).

Is there a possibility to force this. Can I somehow let my script ask for root permissions if I run it under my own username?

share|improve this question

migrated from stackoverflow.com Jan 6 '12 at 14:56

This question came from our site for professional and enthusiast programmers.

3 Answers 3

up vote 5 down vote accepted

I have a standard function I use in bash for this very purpose:

# Check if we're root and re-execute if we're not.
rootcheck () {
    if [ $(id -u) != "0" ]
    then
        sudo "$0" "$@"  # Modified as suggested below.
        exit $?
    fi
}

There's probably more elegant ways (I wrote this AGES ago!), but this works fine for me.

share|improve this answer
    
Possibly exec sudo "$0" "$@" to avoid problems with spaces in arguments, and avoid have the first execution hanging around? –  Douglas Leeder Sep 23 '10 at 9:33
    
Yeah, that would be a decided improvement. I'll update the answer to reflect it. –  JUST MY correct OPINION Sep 23 '10 at 10:11
    
Note that if it's run as a function like this, you need to pass in the script's parameters (i.e. run it with rootcheck "$@"). Or you can just put the if block inline rather than in a function. Also, this should be done very early in the script, as anything before it will be run twice (once normally, once as root). –  Gordon Davisson Sep 23 '10 at 19:18
    
I do it first thing in the script, so yeah. Early is right. –  JUST MY correct OPINION Sep 24 '10 at 0:11
    
It's sometimes good to run sanity checks (e.g. does the file in question exist?) before sudo'ing -- I tend to do this by starting the script with something like if [[ $1 == "--no-sanity-checks" ]]; then shift; else run sanity checks; fi and then modify the sudo command to exec sudo "$0" --no-sanity-checks "$@" –  Gordon Davisson Sep 25 '10 at 17:28
sudo chown root yourcode
sudo chmod 500 yourcode

Voila!

share|improve this answer

You can change the permissions, so that only root can execute it. Or you could use whoami command and in case that it isn't root force sudo.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.