How to run nohup and write its pid file in a single bash statement

LinuxBash

Linux Problem Overview


I want to run my script in background and then write its pid file. I am using nohup to do this.

This is what i came up with,

nohup ./myprogram.sh > /dev/null 2>&1 & && echo $! > run.pid 

But this gives a syntax error.

The following doesn't give syntax error but the problem is echo $! doesn't write the correct pid since nohup is run in a sub shell

(nohup ./myprogram.sh > /dev/null 2>&1 &) && echo $! > run.pid 

Any solutions for this, given i want a single line statement for achieving this?

Linux Solutions


Solution 1 - Linux

You already have one ampersand after the redirect which puts your script in background. Therefore you only need to type the desired command after that ampersand, not prefixed by anything else:

nohup ./myprogram.sh > /dev/null 2>&1 & echo $! > run.pid

Solution 2 - Linux

This should work:

nohup ./myprogram.sh > /dev/null 2>&1 &
echo $! > run.pid

Solution 3 - Linux

Grigor's answer is correct, but not complete. Getting the pid directly from the nohup command is not the same as getting the pid of your own process.

running ps -ef:

root     31885 27974  0 12:36 pts/2    00:00:00 sudo nohup ./myprogram.sh
root     31886 31885 25 12:36 pts/2    00:01:39 /path/to/myprogram.sh

To get the pid of your own process, you can use:

nohup ./myprogram.sh > /dev/null 2>&1 & echo $! > run.pid
# allow for a moment to pass
cat run.pid | pgrep -P $!

Note that if you try to run the second command immediately after nohup, the child process will not exist yet.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionamitkarmakarView Question on Stackoverflow
Solution 1 - LinuxGrigor YosifovView Answer on Stackoverflow
Solution 2 - LinuxanubhavaView Answer on Stackoverflow
Solution 3 - LinuxMor BlauView Answer on Stackoverflow