首页 文章

bash ps打印有关名称的进程的信息

提问于
浏览
3

我需要使用带有类型名称的进程ps打印UID PID PPID PRI NI VSZ RSS STAT TTY TIME列 .

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

但是,当我使用带有参数$ 2 = bash的此命令时,它没有打印任何内容(此过程存在)

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

这对我有用,但实际上这个解决方案恕我直言并不是最好的 . 我使用shadow column命令,在grep名称和打印所有列之后排除命令 .

1 回答

  • 4

    您始终可以使用两阶段方法 .

    1.)找到想要的 PID . 为此使用最简单的 ps

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

    ps -o pid,comm 只打印两列,如:

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

    所以很容易(和 noise-less ,没有错误的触发器) . cut 只是提取PID . 例如 . 该

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

    版画

    67676
    71548
    71995
    74364
    

    2.)现在你可以使用 -p 标志将找到的 PIDs 提供给另一个 ps ,因此完整的命令是:

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

    产量

    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
    

    例如使用 $2 的解决方案是

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

相关问题