← Back to all snippets
BASH

Manage Background Processes and Log Output in Bash

Learn to run long-running commands in the background of your Bash scripts, effectively track their Process ID (PID), and redirect their standard output and error streams to specific log files.

#!/bin/bash

LOG_DIR="./logs"
APP_NAME="my_background_app"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
LOG_FILE="$LOG_DIR/${APP_NAME}_${TIMESTAMP}.log"
PID_FILE="$LOG_DIR/${APP_NAME}.pid"

# Create log directory if it doesn't exist
mkdir -p "$LOG_DIR"

# Function to simulate a long-running task
function long_running_task {
  echo "[$(date)] Starting long running task... PID: $$"
  for i in $(seq 1 5); do
    echo "[$(date)] Task step $i..."
    sleep 2
    if [ $(( RANDOM % 10 )) -eq 0 ]; then
      echo "[$(date)] Simulating an error at step $i." >&2
    fi
  done
  echo "[$(date)] Long running task finished."
}

# Start the task in the background, redirecting stdout and stderr to the log file
echo "Starting '$APP_NAME' in the background. Logging to '$LOG_FILE'."
long_running_task > "$LOG_FILE" 2>&1 &

# Capture the Process ID (PID) of the last background command
BACKGROUND_PID=$!

# Save the PID to a file
echo "$BACKGROUND_PID" > "$PID_FILE"
echo "Process ID $BACKGROUND_PID saved to $PID_FILE"

echo "You can monitor the log file: tail -f $LOG_FILE"
echo "To stop the process manually: kill $BACKGROUND_PID"

# Wait for the background process to complete (optional)
# For a real daemon, you might exit here and let the process run independently
# If you need to wait, you can use: wait $BACKGROUND_PID

# Example of how to later check or kill the process
# if [ -f "$PID_FILE" ]; then
#   read -r running_pid < "$PID_FILE"
#   if ps -p "$running_pid" > /dev/null; then
#     echo "Process $running_pid is still running."
#     # kill "$running_pid"
#     # rm "$PID_FILE"
#   else
#     echo "Process $running_pid is not running (stale PID file)."
#   fi
# fi

wait $BACKGROUND_PID
echo "Background process $BACKGROUND_PID completed. Check logs in $LOG_FILE"
How it works: This snippet demonstrates how to run a command or function in the background, manage its Process ID (PID), and redirect its output to a log file. Appending `&` to a command runs it in the background, and `$!` captures its PID. `> "$LOG_FILE" 2>&1` redirects both standard output and standard error to the specified log file, ensuring all task activity is recorded. Storing the PID in a file (`PID_FILE`) allows for later monitoring or graceful termination of the background process, which is crucial for server-side applications or long-running automation tasks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs