Ubuntu: writing a bash script that uses sudo [duplicate]


This question already has an answer here:

I am sure that this is a very basic question but I'm afraid that I have been unable to get it to work or understand what is going on.

I have a node project that I usually run with

sudo npm start  

and I am trying to create a bash script that will launch this for me.

I have tried a few variations:

su myname -c "npm run start"  sudo su myname -c "npm run start"  su myname -c "sudo npm start"  

but they all seem to execute the command without superuser rights. From the research that I have done it seems that

sudo su myname -c "npm run start"  

is the correct one but it doesn't work (it runs but without permissions). Can someone please point me in the right direction?


Don't use plain sudo in scripts, run the whole script with root permissions instead and use sudo -u YOURUSERNAME to execute commands without root permissions if that's really necessary.

Write a script like this:

#!/bin/bash  npm start  

Save it, make it executable with chmod +x /path/to/script and start it with root permissions with:

sudo /path/to/script    # from a terminal  gksudo /path/to/script  # without terminal (e.g. for a starter)  kdesudo /path/to/script # without terminal, KDE equivalent  

That's all what it takes.

You may add further commands to the script, you could for example check whether it was started as root and exit else (thanks to PerlDuck):

[[ $EUID -ne 0 ]] && echo "This script must be run as root." && exit 1  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »