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?


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" ]
        sudo "$0" "$@"  # Modified as suggested below.
        exit $?

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

To use this function consistently in a script, you should pass it the arguments received by the script originally.

Usage: rootcheck "${@}" (rootcheck alone will not pass any arguments to the rootcheck function)

| improve this answer | |
  • 1
    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

i am using this single line version, easy to copy paste on top of scripts

[ `whoami` = root ] || { sudo "$0" "$@"; exit $?; }
| improve this answer | |
  • 1
    This would work, but it creates a dependency on sudo. It's probably better form to just check $EUID and quit if not root. – HalosGhost Sep 2 '14 at 21:15
sudo chown root yourcode
sudo chmod 500 yourcode


| 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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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