Bash – Getting the process-id out of command launched with “su -c”

bashshellsu

I am running a java program inside a shell and writing the process-id to a text file.
So when I do this:

nohup java app.Main > /dev/null 2>&1 &
echo $! > /var/run/app.pid

It works. But I really want to run it as another user

su - appuser -c "nohup java app.Main > /dev/null 2>&1 &"
echo $! > /var/run/app.pid

This doesn't work. Is there any way of getting the process-id of the command launched with the -c option?

Best Answer

You can do:

su - appuser -c 'nohup java app.Main > /dev/null 2>&1 &
                 echo "$!"' > /var/run/app.pid

(that assumes the login shell of appuser is Bourne-like).

su - resets the environment, so if you want to have variables expanded in the command line, it has to be done by your shell (not the login shell of the remote user) like:

su - appuser -c "nohup '$JAVA_BIN' '$JAVA_CLASS' > /dev/null 2>&1 &"'
                 echo "$!"' > /var/run/app.pid

(that assumes those variables don't contain single quote characters).

You want the redirection to be performed by your shell (running as root), not appuser's shell (which probably doesn't have write permission to /var/run).

Related Question