BASH
Run Bash Commands in the Background Reliably with nohup
Use `nohup` and `&` to run long-running commands or services in the background, ensuring they continue even after logging out.
#!/bin/bash
# --- Configuration ---
LOG_DIR="/var/log/my-app"
APP_SCRIPT="./my-long-running-script.sh" # Replace with your actual script/command
mkdir -p "$LOG_DIR"
OUT_LOG="$LOG_DIR/app_output.log"
ERR_LOG="$LOG_DIR/app_error.log"
echo "Starting script '$APP_SCRIPT' in background..."
# Run the command in the background, redirecting stdout/stderr to log files
# nohup ensures the command continues to run even if the terminal is closed
# > "$OUT_LOG" redirects stdout to app_output.log
# 2>&1 redirects stderr (file descriptor 2) to the same location as stdout (file descriptor 1)
# & puts the entire command into the background
nohup "$APP_SCRIPT" > "$OUT_LOG" 2>&1 &
# Capture the Process ID (PID) of the background process
PID=$!
echo "Process '$APP_SCRIPT' started with PID: $PID. Output logged to $OUT_LOG"
# You can now log out, and the process will continue.
# To check its status: ps -fp $PID
# To stop it: kill $PID
How it works: This script demonstrates how to run a command or script in the background using `nohup` and the `&` operator. `nohup` prevents processes from being terminated when the user logs out, making it ideal for long-running server tasks or starting web application services. Standard output and error are redirected to specified log files for monitoring, and the script captures the process ID (`PID`) for later management.