5

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.

Andrii Tytarenko
  • 121
  • 1
  • 10
  • you have missed the `comm` column (`comm` - just the command name - best for `grep bash`, `cmd` - command with arguments, `grep bash` would fail) – Dima Chubarov Apr 13 '17 at 17:10
  • instead of the long `awk` command, you can use `cut -d',' -f-9`. Better than that, to avoid `awk`/`cut`, you can use `ps o uid,pid,(...),tty,time $(pgrep $2)` – silel Apr 13 '17 at 17:56

1 Answers1

7

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' ')
clt60
  • 62,119
  • 17
  • 107
  • 194