How to run a command as a specific user in an init script?
If you have start-stop-daemon
start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
For systemd style init scripts it's really easy. You just add a User= in the [Service] section.
Here is an init script I use for qbittorrent-nox on CentOS 7:
[Unit]
Description=qbittorrent torrent server
[Service]
User=<username>
ExecStart=/usr/bin/qbittorrent-nox
Restart=on-abort
[Install]
WantedBy=multi-user.target
On RHEL systems, the /etc/rc.d/init.d/functions
script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.
The specific function provided to help with this is daemon
. If you are intending to use it to start a daemon-like program, a simple usage would be:
daemon --user=username command
If that is too heavy-handed for what you need, there is runuser
(see man runuser
for full info; some versions may need -u
prior to the username):
/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"
Instead of sudo, try
su - username command
In my experience, sudo is not always available on RHEL systems, but su is, because su is part of the coreutils package whereas sudo is in the sudo package.