What does a two-stage awk pipeline over ps -ef print?
Given the command below, state exactly what column of data ends up on screen and why. ps -ef prints a process table whose columns are UID PID PPID C STIME TTY TIME CMD.
Constraints: reason about field numbering only; do not run it. Note the second awk re-splits its input on a custom separator.
ps -ef | awk '{print $2":"$8}' | awk -F: '{print $1}'
Determine the output.
It prints the PID column. The first awk joins field 2 (PID) and field 8 (CMD) as PID:CMD. The second awk -F: splits each line on : and prints $1, the part before the first colon — the PID. Because the command can contain colons, only the first colon is the split boundary, so $1 is still the PID. For example 1234:/usr/bin/sshd collapses to 1234.
- ✗Miscounting
ps -effields —$2is PID, not PPID - ✗Thinking
-F:keeps the part after the colon instead of$1before it - ✗Forgetting only the first
:splits, so a command with colons is safe
- →How would you change the pipeline to print the command instead of the PID?
- →Why is piping
psoutput toawkfragile if a column value contains spaces?
Solution
ps -ef prints a table with columns UID PID PPID C STIME TTY TIME CMD, so $2 is the PID and $8 is the command.
ps -ef | awk '{print $2":"$8}' | awk -F: '{print $1}'
e.g. 1234:/usr/bin/sshd.
the part before the first colon, i.e. 1234.
- The first
awkprints$2":"$8for each line — that isPID:CMD, - The second
awk -F:sets the field separator to:and prints$1—
The result is the PID column of every process. Even when the command contains colons (1234:/a:b), only the first colon is the split boundary, so $1 remains exactly the PID.