Bash脚本提供不需要的输出

Bash脚本提供不需要的输出,bash,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.s

我面临以下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等)

这是正常的,因为
$processname
Firefox
。因为您的命令也监视它,所以有一个进程使用它

例如,尝试
ps-el | grep Firefox
,您将得到两个匹配的进程行(如果您有一个运行Firefox的实例),一个是Firefox,另一个是grep命令查找Firefox

grep-v/bin/bash'
中管道化输出应该可以解决这个问题。例如:

ps -el | grep $processname | awk ...
变成:

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

这是正常的,因为
$processname
Firefox
。因为您的命令也监视它,所以有一个进程使用它

例如,尝试
ps-el | grep Firefox
,您将得到两个匹配的进程行(如果您有一个运行Firefox的实例),一个是Firefox,另一个是grep命令查找Firefox

grep-v/bin/bash'
中管道化输出应该可以解决这个问题。例如:

ps -el | grep $processname | awk ...
变成:

ps -el | grep $processname | grep -v 'grep' | awk ...
你在打电话吗

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 filter

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 filter,常见的技巧是将
grep Firefox
更改为
grep[F]irefox
。在这种情况下,您可以使用

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

常见的技巧是将
grep-Firefox
更改为
grep[F]irefox
。在这种情况下,您可以使用

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

好的,我试过这个,它也能工作:ps-el | grep$processname | awk'{if($15!=“grep”)print进程消耗的内存“$15”是=“$9}”| grep-v/bin/bash>>out.logOk我试过这个,它也能工作:ps-el | grep$processname | awk'{if($15!=“grep”)print进程消耗的内存“$15”是=“$9}“| grep-v/bin/bash>>out.log您将使用bash-here字符串:
grep$processname您将使用bash-here字符串:
grep$processname