The Stack Overflow podcast is back! Listen to an interview with our new CEO.
1 of 2

I worked out the following one-liner to accomplish this; there may be a better way. The regex /bash/ is what selects the process name to match.

ps -ef | awk ' NR == 1 { header = $0; next } { pid[$2] = $0 } /bash/ { toprint[$2] } END { print header; for (i in toprint) { while (i != 1) { split(pid[i], pieces, " "); i = pieces[3]; toprint[i] } } for (i in toprint) { print pid[i] } }'

I actually worked this out first as a full script and then condensed it to a one-liner; here is the more readable version:

ps -ef | awk '
NR == 1 {
  header = $0
  next
}
{
  pid[$2] = $0                    # Save all lines of ps -ef in this array, stored by PID
}
/bash/ {                          # Modify this regex to change the filter
  toprint[$2]                     # Designate all these PIDs as "to print"
}
END {
  print header
  for (i in toprint) {            # For each PID designated "to be printed":
    while (i != 1) {
      split(pid[i], pieces, " ")  # Look up the info on that process
      i = pieces[3]               # Set i to the PPID
      toprint[i]                  # Designate that PPID as "to print"
    }                             # Recurse to get the parent of that process, until PID 1 is reached.
  }
  for (i in toprint) {            # Then actually print the data.
    print pid[i]
  }
}'