Bash scripts requiring sudo password

Viewed 27450

I'm creating a Bash installer script which compiles and installs some libraries for both OSX and Linux. Because some commands in my script ("make install", "apt-get install", "port install", etc) require sudo, I need the user to supply the password.

Currently the user gets asked for the password whenever the first sudo command is about to execute, but because this is often after a compile stage, there is always some time between starting the script and having to enter the password.

I would like to put the password entry + check at the beginning of the script. Also I am curious if this is really an ok way of installing system libraries.

Alternatively I could install the libraries in a local sandbox location which doesn't require sudo, but then I'll have to tell apt-get and macports where to install their libraries other then the default /usr/local/ and /opt/local, and I'm not sure how to do that nor if that's a clever idea at all.

4 Answers

Another way to go about it :

function checkSudo() {
    if ((EUID != 0)); then
        echo "Granting root privileges for script ( $SCRIPT_NAME )"
        if [[ -t 1 ]]; then
            sudo "$0" "$@"
        else
            exec 1>output_file
            gksu "$0" "$@"
        fi
        exit
    fi
}

Maybe a bit easier to read:

[ $(whoami) == "root" ] || exit
Related