2017-04-13 96 views
2

我需要打印UID PID PPID PRI NI VSZ RSS STAT TTY TIME使用ps鍵輸入名稱的進程。bash ps打印有關進程名稱的信息

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 

這對我的作品,但實際上這種解決方案恕我直言,不是最好的。我使用陰影列命令,在什麼grep名字後打印所有不包括命令的列。

+0

你已經錯過了'comm'列('comm' - 只是命令的名字 - 最好的'grep的bash','cmd' - 命令參數,'grep的bash'會失敗) –

+0

而不是長'awk'命令,您可以使用'cut -d','-f-9'。更好的是,爲了避免'awk' /'cut',你可以使用'ps o uid,pid,(...),tty,time $(pgrep $ 2)' – silel

回答

1

您可以隨時使用兩階段方法。

1.)找到想要的PID s。對於這種使用盡可能簡單的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 

所以grepping很容易(和噪音少,沒有錯誤觸發)。 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' ') 
+0

謝謝!這真的對我很好,很好的解決方案! –