Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

thers a similar question out there How can I determine whether a shell-script runs as root or not?

I have the same doubt with different result

Is it possible to, within the BASH script prior to everything being run, check if the script is being run as superuser, and if not, print a message saying You must be superuser to use this script, then subsequently

get pass from the user using askpass or something like that then execute the same script as superuser?

share|improve this question
    
Potential duplicate of my question, no? – Thomas Ward Mar 14 '11 at 6:48
    
@EvilPhoenix: the question is not "how to detect that I am root" but "how can I make a script root through a mechanism like sudo". – Lekensteyn Mar 15 '11 at 8:45
    
up vote 10 down vote accepted

I just call sudo if the program needs root permissions, but doesn't have:

#!/bin/bash
if [ $(id -u) != 0 ]; then
   echo "This script requires root permissions"
   sudo "$0" "$@"
   exit
fi

"$0" contains the name of the script, "$@" optional arguments. It may be omitted if your program does not accept arguments.

Note: this shellscript is expected to be run in a shell, if this script should run as GUI, use something like gksu or kdesudo instead of sudo.

share|improve this answer

this does not work although Lekensteyn is right on point.

you have to set the variable equal to the output of id -u

ID=$(id -u) if [ $ID != 0 ] then sudo "$0" "$@" exit fi

if you use echo to output this script requires root permissions that will show up every time a user other than root(since its id=0) runs the script regardless of whether or not it needs root permissions, so just keep it simple.

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.