bash script ask for root password

Solution 1:

Just use the sudo word in front of the command in the bash script. And when you execute the file, select "Open in terminal", you will be asked for password.

For example, if you are using apt-get commands , you can use like this

#!/bin/sh
sudo apt-get update
sudo apt-get upgrade
.....
.....

If need to make this executable and when you double click there will be a prompt like this

enter image description here

You need to click on Open in terminal button and provide password in the terminal

Update

As Karthick T commented, you can also use the gksu or gksudo word before the command. So, the file could be

gksu apt-get update
gksudo apt-get install <some-package>

Double clicking the script will ask the password and run the command after you provided it.

Solution 2:

I've had to do this several times, this is a template of my scripts that need to run as root and prompt the user for the root password.

#!/usr/bin/env bash

cmdname=$(basename $)

function usage() {
    echo
    echo "$cmdname [-l|--location] /location/to/package [-p|--no-provisioning]"
    echo "  -l | --location     Set the location to be used to find the package install"
    echo "  -p | --no-provision If set, will not load the example provisioning"
    exit 1
}

if [ "$(whoami)" != "root" ]; then
    echo "You must be root to do this"
    su -c "$0 $*"
    exit
fi

LOCATION="/tmp/TESTPKG$USER/"
PROVISION=1

OPTIONS=$(getopt -o l:p --long location:,no-provisioning -n "$cmdname" -- $*) || usage
eval set -- $OPTIONS

while true ; do
    case $1 in
        -l|--location)
            LOCATION=$2
            shift 2;;
        -p|--no-provisioning)
            PROVISION=0
            shift 1;;
        --) shift ; break ;;
        *)
            echo "Invalid argument $1"
            exit 1;;
    esac
done

The above is for a specific use case, but I think it highlights two nice features, using getopt and asking for root permission and running command, while passing in the arguments.

So the if block check if the user is currently root, if not, runs the called script ($0) with any arguments passed to the script ($*). Then it exits, as to not attempt to run the script as the non-root user.

The getopt line attempts to then parse the options and if there is an invalid argument it prints the usage and exits.