2012-02-10 119 views
1

我用下面的bash腳本面對:bash腳本給不需要的輸出

#! /bin/bash 
processname=$1 
x=1 
while [ $x -eq 1 ] ; do 
    ps -el | grep $processname | awk ' {if($15!="grep") print "The memory consumed by the process " $15 " is = "$9} ' >> out.log 
    sleep 30 
done 

,我與運行以下命令:

$ ./myscript.sh Firefox 

,但是當我看到文件中的輸出,除了該firefox過程中我也得到信息/bin/bash過程

The memory consumed by the process /Applications/Firefox.app/Contents/MacOS/firefox is = 911328 
The memory consumed by the process /bin/bash is = 768 

有人可以幫助我,因此我只想獲取有關Firefox進程的信息(/bin.bash等)

回答

2

這是正常的,因爲$processnameFirefox。由於你的命令也監視它,所以有一個使用它的過程。

例如,嘗試ps -el | grep Firefox,您將得到兩個匹配的流程行(如果您有一個運行Firefox的實例),一個是Firefox,另一個是查找Firefox的grep命令。

grep -v /bin/bash'中配管您的輸出應解決此問題。例如:

ps -el | grep $processname | awk ... 

變爲:

ps -el | grep $processname | grep -v 'grep' | awk ... 
+0

好實現它,我嘗試這樣做,它也可以工作: PS -el | grep $ processname | awk'{if($ 15!=「grep」)print「進程使用的內存」$ 15「is =」$ 9}'| grep -v/bin/bash >> out.log – lancelot 2012-02-10 13:10:35

1

你叫

ps -el | grep $processname | awk ' {if($15!="grep") print "The memory consumed by the process " $15 " is = "$9} ' 

這意味着,在運行awk和連接它的使用grep的輸出輸入。然後grep啓動並獲取ps -el的輸出作爲輸入。

在bash啓動ps的那一刻,你已經運行了grep和awk。

解決方法:運行ps -el並記住它的輸出。然後運行grep和awk。它應該是這樣的:

ps -el > ps.tmp 
grep $processname ps.tmp | awk ' {if($15!="grep") print "The memory consumed by the process " $15 " is = "$9} ' >> out.log 

也許這可以不使用tmp文件來完成。像TMP=$(ps -el)。但我不知道如何在變量上運行grep過濾器

+0

你可以使用bash here-string:'grep $ processname <<<「$ tmpvar」| ...' – 2012-02-10 14:44:27

+0

謝謝格倫!這樣可行! – 2012-02-10 14:50:44

3

常見的技巧是將grep Firefox更改爲grep [F]irefox。在這種情況下,你可以用

ps | grep '['${processname:0:1}']'${processname:1} 
+0

+1,非常棒! – 2012-02-11 18:08:12