2011-09-17 40 views
3

我在嘗試一些非常簡單的事情,並且遇到了很多麻煩。比較在bash中的PID

我有一個bash腳本,我必須爲類執行類似於pstree的類編寫腳本。它爲自己報告pstree。輸出應該是這樣的:

PID 
| 
PPID 
| 
. 
. 
. 
| 
1 

這裏是我到目前爲止的代碼:

ps -ef>tmp1.txt     #save ps -ef to a file 
pid=$$  
echo $pid       #print first PID 
while [ $pid != "1" ] 
do 
    cat tmp1.txt | while read line #read in ps -ef file line by line 
    do 
     tmp=$(echo $line | cut -f2 -d' ') #return only the PID column of ps -ef 
     if [$pid == $tmp]     #compare current PID to temp PID of current line 
     then 
      echo "|" 
      pid=$(echo $line | cut -f3 -d' ') #if they're the same we found the PPID, so save it 
      echo $pid       #and echo it 
     fi 
    done 
done 

如果它的失敗是在比較聲明:

if [$pid == $tmp] 

我得到一個未找到錯誤。有任何想法,爲什麼比較不起作用?感謝提前提供任何幫助,如果我能澄清任何事情,請告訴我。

回答

4

單個等號用於比較字符串(if [ $pid = $tmp ])。

+3

而且你需要'['和']'字符周圍的空格。 –

+0

@凱斯:對,謝謝,我寫得很對,但沒有指出來。 –

+0

好吧,做了這個改變加上我在它後面加了分號。仍然不完全工作,但我正在取得進展。謝謝你們 – Casbar77

2

我編輯了你的問題來縮進代碼。當你每次縮進和如果聲明時,閱讀起來要容易得多。

你在抱怨該生產線是

if [$pid == $tmp] 

說了兩個原因已經指出的無效。與其他編程語言不同,BASH使用一個等號,並且您必須在方括號周圍留空格。方括號是一個命令,並且必須分隔空格。這是test命令的別名。這條線應該是這樣的:

if [ $pid = $tmp ] 

現在,=是一個字符串比較,如果你正在做一個數字比較,你應該使用-eq代替:

if [ $pid -eq $tmp ] 

而且,由於[是別名到test命令,它可以被寫成這樣(但很少是):

if test $pid -eq $tmp 

但是,它不會告訴你爲什麼你ñ在方括號周圍留下空間。

+0

感謝您的反饋以及縮進代碼。缺少縮進是一個複製和粘貼問題。我在太多的環境中移動,忘記將它們添加回來。 – Casbar77

0

您的代碼效率不高。嘗試使用awk,沒有臨時文件和嵌套循環:

ps -eo pid,ppid | awk -v START=$$ ' 
{ PPID[$1]=$2 } # (for each line) create PPIDs table record 
END { if (PPID[START]) { # (when done) if starting pid is correct 
    for(pid=START; pid!=1; pid=PPID[pid]) # print the tree 
     printf "%d\n|\n", pid; 
    print 1; 
    } 
}' 
+0

我知道它效率低下。我被要求用這種方式編碼。不過,我同意你的看法。在awk中做所有這些都是優越的。 – Casbar77

0

對於那些你感興趣的我最終的代碼如下所示:

echo $pid 
while [ $pid != "1" ] 
do 
    while read line 
    do 
      tmp="$(echo $line | cut -f2 -d' ')" 
      if [ $pid = $tmp ]; 
      then 
       pid="$(echo $line | cut -f3 -d' ')" 
      fi 
    done<./tmp1.txt 
    echo "|" 
    echo $pid 
done 

感謝你們所有的人絕地大師那裏。

+0

你仍然可以避免一個臨時文件(總是很麻煩,即使在正常的成功情況下,你似乎也不會刪除它),並在'read'中進行分割。像'ps -ef |同時閱讀店主休息;在$ p中做$ case pid)pid = $ pp ;; ESAC; done' – tripleee