writing a bash script that uses sudo
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
Roaders
Previously a Flex developer now moving into Typescript, NodeJs and HTML5 development.
Updated on September 18, 2022Comments
-
Roaders over 1 year
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?
-
Byte Commander over 6 yearsJust
sudo npm start
? Why do you think you need anything else? -
PerlDuck over 6 yearsDo you want to run
npm start
asroot
or asmyname
? (To confuse you even more: there's alsosudo -u myname npm start
;-))
-
-
PerlDuck over 6 yearsThis will run the whole script as
root
. Not sure whether that's what the OP intended (in case it contains more commands than justnpm start
). The other way would be to run the script asmyname
and putsudo npm start
into the script. We don't know. -
PerlDuck over 6 yearsI 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. -
dessert over 6 years@PerlDuck Thanks, I did some edits. Even if only one command needs root permissions the whole script should still be run as root IMO.
-
PerlDuck over 6 yearsYou'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 over 6 yearsRe "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 asmyname
. It just depends, I think.