Linux – How to run a program as another user properly with “nohup” and “&” in bash

background-processbashlinuxnohup

I have been learning bash and linux administration over the past few months while producing more and more code that needs to run in the background. I would ideally like to run my development system closer to where it would be in production in order to avoid having to redevelop code due to security and permissions problems.

Generally, I would run something with:

$nohup <program> <program args> >> <program logfile> 2>&1 &

I.e.:

$nohup ping 192.168.0.1 >> ping.log 2>&1 &

However, today I tried to set it up properly by creating a user and giving them the correct permissions to only be able to access their own files and nothing else. It seems like a sensible security practice.

I would do it like so:

$sudo -u <program user> nohup <program> <program args> >> <program logfile> 2>&1 &

However, this results in the following output when I run ps aux | grep <program>:

<admin user>@server:~$ ps aux | grep <program>
root      1396  0.0  0.0  61868  3792 pts/38   S    10:50   0:00 sudo -u <program user> nohup <program> <program args>
<program user>  1397  0.0  0.8 1273232 68308 pts/38  Sl   10:50   0:02 <program> <program args>

The problem is the first line in the output: ideally, I would like to be able to run these programs without starting any processes with root-level permissions. How do I do that?

Best Answer

you can do it that way :

su - user -c "nohup ping 192.168.122.1 >> ping.log 2>&1 &"