I'm using ps -eo ppid,pid,cmd to view all process, and how can I format the output to view like below?

Only given PID and its ancestor will print (until init).

23464   current
23211   bash
23210   sshd: xxW
23193   sshd: WWcccv
 728    /usr/sbin/sshd –D
  1     init

I'm writing a script to view ancestral process using PID without using pstree, if possible.


Maybe something like:

#! /bin/bash -
pid=${1?Please give a pid}
  [ "$pid" -gt 0 ] &&
    read -r ppid name < <(ps -o ppid= -o args= -p "$pid")
  printf "$sep%$((3+${#pid}/2))d%$((4-${#pid}/2))s%s\n" "$pid" "" "$name"
  sep=$'  |\n'

Which gives:

$ that-script "$$"
13612  /bin/zsh
 4137  SCREEN screen -xRS main
 4136  screen screen -xRS main
 4130  zsh
 4128  xterm
  1    /sbin/init splash

That's a bit sluggish as it runs one ps per process in the ancestry. You can improve it by running ps to retrieve all the information at once and post process it with awk for instance:

#! /bin/sh -
pid=${1?Please give a pid}
ps -Ao pid= -o ppid= -o args= |
  awk -v p="$pid" '
      pid = $1; ppid[pid] = $2
      sub(/([[:space:]]*[[:digit:]]+){2}[[:space:]]*/, "")
      args[pid] = $0
    END {
      while (p) {
        printf "%s%*d%*s%s\n", sep, 3+length(p)/2, p, 4-length(p)/2, "", args[p]
        p = ppid[p]
        sep = "  |\n"

What about using pstree -spa ? It will show both predecessors and ancestors for the given pid, including pid and command lines.

$ pstree -spa 3056
  • that's the answer I was looking for. pstree -spa $$ uses the shell's PID as a start – Johannes Bittner Jul 28 '19 at 1:01

Place pid, ppid's into array. Recursive function or loops to walk through the array, printing only the desired pid and ppid entries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.