The Computer Oracle

Run part of a bash script as a different user

-------------------------------------------------------------------------------
Become or hire the top 3% of the developers on Toptal https://topt.al/25cXVn
-------------------------------------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping

--

Chapters
00:00 Question
00:29 Accepted answer (Score 57)
00:59 Answer 2 (Score 12)
01:25 Answer 3 (Score 8)
02:20 Answer 4 (Score 4)
02:55 Thank you

--

Full question
https://superuser.com/questions/93385/ru...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#linux #bash #user

#avk47



ACCEPTED ANSWER

Score 61


Use the sudo command in the script.

In the form:

sudo -u username command

the sudo command runs command as the user username.

If the script is being run as root, I don't think it will prompt for a password. Otherwise, this article discusses how to use sudo with password in one command line?, and this article discusses how to use sudo without password?




ANSWER 2

Score 12


# I=like:

#test if running bash as a different user works
sudo -u nobody bash -c : && RUNAS="sudo -u nobody"

echo 1: $USER

#Runs bash with commands between '_' as nobody if possible
$RUNAS bash<<_
echo 2: \$USER
_

echo 3: $USER

# ./run

1: root
2: nobody
3: root



ANSWER 3

Score 8


This answer is good, but the serverfault advice is slightly dangerous - would allow anyone to run anything as root! So I'm posting here because I can't format the comment.

I would recommend using visudo to give the permissions you need as precisely as you can. Type visudo and add a line like:

username hostname = NOPASSWD: /full/path/to/command1, full/path/to/command2

If you do need to run this same thing on many hosts, you could open it up with:

username ALL = NOPASSWD: /full/path/to/command1, full/path/to/command2

But I would **not* use either:

username ALL=(ALL) NOPASSWD: ALL

or username hostname = ALL

The sudoer man page has lots of gory details




ANSWER 4

Score 4


For sonarqube:

sudo -u sonar /usr/bin/sonar start

where sonar is the name of user used to run the command /usr/bin/sonar start