I want to make a script and add this to a shortcut launcher...
When i double click the icon, it will popup a terminal window (done)

In the terminal, it will ask for root password at first and then do some stuff with root privilege (I want to make it as a function).

After that, at the end of the script, it will close the window like "press any key to close window" (I can do it)

sudo -S touchpad # but it return error "command not found"

How to run a function as root user or is there another way to accomplish this?

I have tried this #!/bin/bash

sudo ./main2.sh #this did not work when I made it as a launcher

This is my current code (after googling):


gksudo -m "Input Password" clear
sudo whoami
#sudo bla bla bla
read -n 1 -p "Press any key to close window"

This is what I want, but got an error when I type the wrong password for 3 times. How to force quit the main window if gksudo fail??

5 Answers 5


Test the return value of gksudo:

if ! gksudo -m "Input Password" clear ; then
    echo Bad password
    exit 1

IMHO ... Simplest way to run the entire script as root without having to remember that it needs to be run as root It seems like it should work for what you are trying to accomplish

if [[ ${UID} -gt 0 ]] ; then
    sudo ${dScript}
### the rest of your script

You can't. To do it, you need to put the function in another script, and run that script with sudo.

Sudo only runs commands, it cannot access functions inside your script, as it runs in a separate process. If you insist on running a function in your script, you could run the script again with sudo, but pass it an argument with $1 that runs the function directly.

  • i have try to put my function in another script, it works when i acces it via terminal. but when make it as a launcher(application interminal) in panel it didn't works... see my edit.. May 11, 2011 at 7:16
  • 2
    Please try it using the full pathname: sudo FULL_PATH_TO/main2.sh . When called from the launcher the initial working directory is not the script directory, using ./main2.sh is not expected to work. May 11, 2011 at 11:42

what about using gksudo instead? It will prompt user for entering password. Then it should work with just sudo.


You actually can do that:

Assuming that you are logged in as a root user and you want to run a function for a different user other than root, you can use export -f option in your script for that function. For example:


   echo "Hello!! $(whoami)";
  export -f whomomlikes;
  su $user -c "bash -c whomomlikes";

Not that it would only work for the exported function, if you have variables declared in other functions then you have to export them similarly and then run them accordingly.

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.