How to Sort ps Command Output by Process Start Time in Linux/SysV/Mac: Best Methods


3 views

When troubleshooting system performance or monitoring long-running processes, sorting by process start time becomes crucial. The standard ps command doesn't directly offer this sorting capability, requiring some command-line finesse.


# Show full process list sorted by start time (newest first)
ps -eo pid,lstart,cmd --sort=-start_time

# Compact version showing just PID and command
ps -eo pid,cmd --sort=-start_time

# Alternative using BSD-style syntax
ps ax -o pid,command,lstart --sort=-lstart

Older SysV implementations require parsing the /proc filesystem:


ls -ltu /proc/*/ | awk '/^d/ {print $9}' | cut -d/ -f3 | xargs -I{} ps -p {} -o pid,stime,cmd

macOS's BSD-derived ps requires different flags:


# Basic view
ps -ax -o pid,command,lstart | sort -k6,7

# Detailed view with header
ps -ax -o pid,command,lstart | (read -r; printf "%s" "$REPLY"; sort -k6,7)

# Watch processes sorted by start time (Linux)
watch -n 1 "ps -eo pid,cmd,lstart --sort=-start_time | head -n 20"

# Continuous monitoring with timestamps
while true; do
  clear
  date
  ps -eo pid,cmd,lstart --sort=-start_time | head -n 15
  sleep 2
done

For frequent use, consider these alternatives:


# Using htop (install if needed)
htop -s START_TIME

# Using atop (more detailed)
atop -s ST

When troubleshooting system performance or analyzing process behavior, sorting by process start time becomes crucial. The standard ps command doesn't directly support sorting by start time, but we can achieve this through various methods across different Unix-like systems.

Modern Linux systems using procfs provide process start time information through /proc/[pid]/stat. The most reliable approach:

ps -eo pid,lstart,cmd | sort -k 5 -k 4 -k 3

For more detailed output with newest processes first:

ps -eo pid,user,lstart,etime,cmd --sort=start_time

On traditional SysV systems, we need to parse the elapsed time and convert it:

ps -eo pid,stime,etime,args | awk '{print $0}' | sort -k 3

BSD-derived systems like macOS require different syntax:

ps -eo pid,command,lstart | awk '{print $0}' | sort -k 5 -k 4 -k 3

For a cross-platform solution that works on most Unix-like systems:

#!/bin/sh
case $(uname) in
    Linux*)   ps -eo pid,lstart,cmd --sort=-start_time ;;
    Darwin*)  ps -eo pid,lstart,command | sort -k 5 -k 4 -k 3 ;;
    SunOS*)   ps -eo pid,stime,etime,args | sort -k 3 ;;
    *)        echo "Unsupported system" ;;
esac

Combine with pstree for better visualization:

ps -eo pid,lstart,cmd --sort=start_time | head -n 10 | pstree -p