1

I am facing with the following bash script:

#! /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

and I am running this with :

$ ./myscript.sh Firefox

but when i see the output in the file, apart from the firefox process i am also getting information for /bin/bash process

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

Can some one help me with this so that I only want to get information related to Firefox process and nothing else(/bin.bash etc)

3 Answers 3

3

The common trick is to change grep Firefox to grep [F]irefox. In this case, you can achieve it with

ps | grep '['${processname:0:1}']'${processname:1}
Sign up to request clarification or add additional context in comments.

Comments

2

This is normal and because the $processname is Firefox. Since your command also monitors it, there is a process that uses it.

For example, try ps -el | grep Firefox and you will get two process lines matching (if you have one instance of Firefox running), one is Firefox, the other is the grep command looking for Firefox.

Piping your output in grep -v /bin/bash' should solve this. Eg:

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

becomes:

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

1 Comment

Ok i tried this and it also works : ps -el | grep $processname | awk ' {if($15!="grep") print "The memory consumed by the process " $15 " is = "$9} ' | grep -v /bin/bash >> out.log
1

You calling

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

This means that you run awk and connect it's input with output of grep. Then grep is started and gets output of ps -el as input.

At the moment when bash will start ps you have grep and awk running.

Solution: run ps -el and remember it's output. Then run grep and awk. It should be like this:

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

Probably this could be done without using tmp file. Like TMP=$(ps -el). But I don't know how to run grep filter on variable

1 Comment

You would use a bash here-string: grep $processname <<< "$tmpvar" | ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.