BudiBadu Logo
Samplebadu

Bash by Example: List Processes

Bash 5.0+

Viewing and filtering running processes using ps command with various formatting options, understanding BSD versus Unix-style flags, using pgrep for name-based process searches, and extracting specific process information for scripting and system monitoring.

Code

#!/bin/bash

echo "--- Standard Snapshot (ps) ---"
# Default ps shows processes in current shell
ps

echo -e "\n--- Full System View (ps aux) ---"
# a = all users, u = user owner, x = terminal-less
# piping to head to show only top 5 lines
ps aux | head -n 5

echo -e "\n--- Custom Format ---"
# Show only PID, User, and Command
ps -eo pid,user,cmd | head -n 5

echo -e "\n--- Search by Name (pgrep) ---"
# Find PIDs of 'bash' processes
pgrep -a bash

Explanation

The ps (process status) command is the primary tool for viewing active processes on a system. Unlike interactive tools like top or htop which provide a real-time updating view, ps provides a static snapshot of the system at the moment it is run. This makes it ideal for scripting and logging purposes where you need to capture the state of the system for analysis or conditional logic.

The flags used with ps can be confusing because it supports three different styles: Unix (preceded by a dash), BSD (no dash), and GNU long options. The most common combination for system administrators is ps aux (BSD style). Here, a shows processes for all users, u displays the user/owner of the process, and x includes processes not attached to a terminal (like daemons). This gives a comprehensive view of everything running on the machine.

For scripting, you often need specific data points rather than a human-readable table. The -o flag allows you to specify exactly which columns you want, such as PID, memory usage, or the command string. Additionally, tools like pgrep are specialized for searching processes by name, which is often cleaner and less error-prone than piping ps output into grep (which might accidentally match the grep process itself).

Code Breakdown

5
Basic ps without arguments shows only processes in the current shell session. Limited but useful for quick checks.
10
ps aux is the standard command to "show me everything running on the system". We pipe to head here just to prevent flooding the screen with hundreds of lines.
14
ps -eo ... allows custom output formatting. This is very useful when you want to parse the output in a loop, e.g., killing processes that exceed a certain memory threshold.
18
pgrep looks up processes based on name and other attributes. The -a flag prints the full command line, not just the PID.