Search code examples
bashunixgreppsnano

bash ps print info about process with name


I need to print UID PID PPID PRI NI VSZ RSS STAT TTY TIME columns using ps of processes with typed name.

  GNU nano 2.0.6                                                     
  File: file2                                                                                                                        

  ps o uid,pid,ppid,ni,vsz,rss,stat,tty,time | grep $2  > $1
  cat $1
  echo "enter pid of process to kill:"
  read pid
  kill -9 $pid

But it prints nothing, when I use this command with argument $2 = bash (this process exists)

UPDATE

  GNU nano 2.0.6                               
  File: file2  

ps o uid,pid,ppid,ni,vsz,rss,stat,tty,time,command | grep $2 | awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}'  > $1
cat $1
echo "enter pid of process to kill:"
read pid
kill -9 $pid

This works for me, but actually this solution IMHO isn't the best one. I use shadow column command, after what grep name and print all columns excluding command.


Solution

  • You can always use the two-stage approach.

    1.) find the wanted PIDs. For this use the simplest possible ps

    ps -o pid,comm | grep "$2" | cut -f1 -d' '
    

    the ps -o pid,comm prints only two columns, like:

    67676 -bash
    71548 -bash
    71995 -bash
    72219 man
    72220 sh
    72221 sh
    72225 sh
    72227 /usr/bin/less
    74364 -bash
    

    so grepping it is easy (and noise-less, without false triggers). The cut just extracts the PIDs. E.g. the

    ps -o pid,comm | grep bash | cut -f1 -d' '
    

    prints

    67676
    71548
    71995
    74364
    

    2.) and now you can feed the found PIDs to the another ps using the -p flag, so the full command is:

    ps -o uid,pid,ppid,ni,vsz,rss,stat,tty,time,command -p $(ps -o pid,comm | grep bash | cut -f1 -d' ')
    

    output

      UID   PID  PPID NI      VSZ    RSS STAT TTY           TIME COMMAND
      501 67676 67675  0  2499876   7212 S+   ttys000    0:00.04 -bash
      501 71548 71547  0  2500900   8080 S    ttys001    0:01.81 -bash
      501 71995 71994  0  2457892   3616 S    ttys002    0:00.04 -bash
      501 74364 74363  0  2466084   7176 S+   ttys003    0:00.06 -bash
    

    e.g. the solution using the $2 is

    ps -o uid,pid,ppid,ni,vsz,rss,stat,tty,time,command -p $(ps -o pid,comm | grep "$2" | cut -f1 -d' ')