Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

People also ask

How do I run a sh file in nohup?

To run a nohup command in the background, add an & (ampersand) to the end of the command. If the standard error is displayed on the terminal and if the standard output is neither displayed on the terminal, nor sent to the output file specified by the user (the default output file is nohup. out), both the ./nohup.

How do I get PID of nohup?

When using nohup and you put the task in the background, the background operator ( & ) will give you the PID at the command prompt. If your plan is to manually manage the process, you can save that PID and use it later to kill the process if needed, via kill PID or kill -9 PID (if you need to force kill).

Can you nohup a bash script?

At its most basic, nohup can be used with only a single argument, the name of the script / command that we want to run. For example if we had a Bash script called test.sh we could run it as so. If the script / command produces standard output, then that output is written to nohup.

What does nohup do in bash?

Nohup, short for no hang up is a command in Linux systems that keep processes running even after exiting the shell or terminal. Nohup prevents the processes or jobs from receiving the SIGHUP (Signal Hang UP) signal. This is a signal that is sent to a process upon closing or exiting the terminal.


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

This should work:

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

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.