When working with the ps
command in Linux, a common requirement is to filter the output while keeping the column headers intact. The default behavior shows headers only for the first line, which disappears when piping to grep
:
ps aux | grep GMC
This loses valuable context about what each column represents.
Here are three effective methods to maintain headers while filtering:
Method 1: Using the --headers flag (ps v3.3.0+)
ps --headers aux | grep -E "PID|GMC"
Method 2: Using awk for precise control
ps aux | awk 'NR==1 || /GMC/'
Method 3: Creating a custom function
Add this to your ~/.bashrc
:
psg() {
ps aux | awk -v pattern="$1" 'NR==1 || $0 ~ pattern'
}
Then use: psg GMC
In the example output:
root 32017 1 83 May03 ? 6-22:01:17 /scripts/GMC/PNetT-5.1-SP1/PNetTNetServer.bin
The 6-22:01:17
does indeed indicate the process has been running for:
- 6 days
- 22 hours
- 1 minute
- 17 seconds
The second column (32017 in the example) is indeed the PID. To terminate:
kill 32017
For graceful termination:
kill -15 32017
For forced termination:
kill -9 32017
For more precise process management:
Find all processes older than 3 days:
ps -eo pid,etime,cmd | awk '{split($2,a,"-"); if(a[1]>=3) print}'
Get full process tree with headers:
ps -f --forest | awk 'NR==1 || /GMC/'
When monitoring processes on Linux systems, developers often need to combine ps
with grep
while keeping the column headers visible. This becomes particularly important when:
- Monitoring long-running processes
- Debugging service issues
- Managing process trees
# Method 1: Using header preservation
ps aux | head -n 1; ps aux | grep GMC
# Method 2: Using BSD-style output format
ps -eo pid,user,cmd | grep -E 'PID|GMC'
# Method 3: Using awk for better control
ps aux | awk 'NR==1 || /GMC/'
The format 6-22:01:17
in ps output indicates:
6-
= 6 days22:
= 22 hours01:
= 1 minute17
= 17 seconds
Key columns in ps
output:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 32017 83.0 2.1 1456788 173496 ? Sl May03 6-22:01:17 /scripts/GMC/PNetT-5.1-SP1/PNetTNetServer.bin
To terminate this process:
kill 32017 # Graceful termination
kill -9 32017 # Forceful termination (use as last resort)
For comprehensive process information:
# Show process tree
pstree -p 32017
# Show open files
lsof -p 32017
# Continuous monitoring
watch -n 1 'ps aux | head -n 1; ps aux | grep GMC'
Consider these modern alternatives:
htop
- Interactive process viewerpgrep
- Process grep utilitysystemctl
- For systemd-managed services