0

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?

dessert
  • 39,982
Roaders
  • 231

1 Answers1

4

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
dessert
  • 39,982
  • 1
    This will run the whole script as root. Not sure whether that's what the OP intended (in case it contains more commands than just npm start). The other way would be to run the script as myname and put sudo npm start into the script. We don't know. – PerlDuck Dec 28 '17 at 18:29
  • I often add code like if [ 0 != $(id -u) ]; then echo "this script must be run as root"; exit 1; fi or something similar to scripts when its crucial who runs them. – PerlDuck Dec 28 '17 at 18:36
  • @PerlDuck Thanks, I did some edits. Even if only one command needs root permissions the whole script should still be run as root IMO. – dessert Dec 28 '17 at 18:54
  • You're welcome. It's a personal habit because I often have scripts that must or must not be run as root (or some other dedicated user) and they often show weird behaviour when started by someone else. – PerlDuck Dec 28 '17 at 19:08
  • 1
    Re "Even if only one command needs root permissions…": I decide that case by case. Sometimes I add an entry to /etc/sudoers for the special command and run the script as myname. It just depends, I think. – PerlDuck Dec 28 '17 at 19:11