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

Learn how to run nohup and write its pid file in a single bash statement with practical examples, diagrams, and best practices. Covers linux, bash development techniques with visual explanations.

Running nohup with PID File Creation in a Single Bash Command

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

Learn how to execute a command using nohup for background execution and simultaneously capture its Process ID (PID) into a file, all within one concise bash statement.

When running long-duration processes on Linux or Unix-like systems, nohup is an indispensable command that allows a process to continue running in the background even after the user logs out. However, managing these background processes often requires knowing their Process ID (PID). This article details how to combine nohup execution with the creation of a PID file in a single, elegant bash command, streamlining your server management tasks.

Understanding nohup and Background Processes

nohup is a POSIX command that makes a command immune to hangups, meaning it will continue to run even if the user who started it logs out. By default, nohup redirects standard output to nohup.out in the current directory if it's not redirected elsewhere. To run a command in the background, you typically append & to the command. Combining these ensures your process runs detached and in the background.

nohup your_command &

Basic nohup usage to run a command in the background

Capturing the Process ID (PID)

After a command is sent to the background using &, bash immediately makes its PID available in the special variable $!. This variable holds the PID of the most recently executed background command. We can leverage this to write the PID to a file. The challenge is to do this immediately after nohup starts the process, before any other command might overwrite $!.

The Single-Statement Solution

To achieve both nohup execution and PID file creation in one line, we combine the nohup command with a redirection for the PID. The key is to ensure the PID is captured right after the nohup command is initiated. Here's the most common and robust approach:

nohup your_command > /dev/null 2>&1 & echo $! > your_command.pid

Running nohup and writing PID to a file in one line

Let's break down this command:

  1. nohup your_command: Executes your_command with nohup.
  2. > /dev/null 2>&1: This redirects both standard output (> /dev/null) and standard error (2>&1) to /dev/null, effectively silencing the command's output. This is often desired for background processes to prevent nohup.out from growing large or to avoid cluttering the terminal.
  3. &: This sends the entire nohup command (including its redirections) to the background.
  4. echo $! > your_command.pid: Immediately after the nohup command is sent to the background, $! contains its PID. This part of the command then echoes that PID and redirects it into a file named your_command.pid.
Hero image for How to run nohup and write its pid file in a single bash statement

Execution flow of the combined nohup and PID capture command

Example Usage

Consider a Python script named my_script.py that runs indefinitely. We want to start it with nohup and store its PID.

# my_script.py
import time
import sys

print("My script started!")

try:
    while True:
        time.sleep(5)
        print("Script still running...", flush=True)
except KeyboardInterrupt:
    print("Script interrupted.")
    sys.exit(0)

Example Python script for background execution

nohup python3 my_script.py > /dev/null 2>&1 & echo $! > my_script.pid

# Verify the PID file
cat my_script.pid

# Check if the process is running
ps -p $(cat my_script.pid)

Executing the Python script with nohup and PID capture

After running the command, my_script.pid will contain the PID of the python3 process. You can then use this PID to manage the process, for example, to stop it using kill $(cat my_script.pid).