Having trouble with a script about detection of processes
I am trying to build a script that detects when you start the implementation of a process whose name is passed as an argument. For this I am using the command ps-ef to list all system processes.
I have this so far: #! /bin/bash # Title: Detection de un proceso # Author: Jose Miguel Colella # Description: Inicion de un proceso while true; do Numero=`ps -ea |grep ${1} | cut -d " " -f 2 | egrep -grep` if test $Numero ; then kill $Numero fi done but it wont process |
On my system the Process ID in the output of ps -ea is the first field, not the second. Moreover it is not clear what egrep -grep means: it throws an error on my system. Anyway, take in mind that you can customize the output of the ps command, forcing it to give only the information you need. For example, if I want to retrieve the PID of a sleep process, I can do:
Code:
ps -C sleep -o pid= |
Hi,
This part looks wrong: ps -ea |grep ${1} | cut -d " " -f 2 | egrep -grep The egrep command is in the wrong place and isn't syntactically correct. The cut command is probably wrong as well. (field 2 vs field 1) The egrep command should be: egrep -v grep. That is assuming you want to get rid of the grep command in the ps -ea output. It also is in the wrong place. After this part ps -ea |grep ${1} | cut -d " " -f 2 you are left with (PID) numbers only, so the egrep will never get rid of the grep command. And egrep isn;t needed here, grep will do. This would be better: ps -ea | grep -v "grep" | grep "${1}" | cut -d " " -f 1 You do realize that this script will keep running until you manually kill it? Hope this helps. |
To get a list of PROCIDs you can do this:
ps -ea | awk '{print $1}' I can't figure out what you are actually trying to do. I'm sorry I couldn't be of more help. |
For Druuna when I try the commands which you suggested, when I execute the script it says line 3: test: too many arguments.
Why is it doing that? and how do I fix it? Sorry for so many questions |
Hi,
If the ps -ea | grep -v "...... line finds more then 1 PID, the test command will fail, it expects 1 item. You can fix that by putting double quotes around the $Numero part. I.e: if test "$Numero" ; then As AwesomeMachine already mentioned, you should use awk '{ print $1 }' instead of the cut command. A working version would look like this: Code:
#!/bin/bash |
I don't really see the need for so many piped commands, when ps options can extract only the necessary information. Moreover it's still not clear if the OP wants to kill multiple instances of the same process (if any).
|
Thanks Druuna you answer helped me a lot
|
Hi,
You're welcome :) One more thing: Do have a look at what colucix posted (post #2). Although sometimes having a solution that works and knowing why it does or doesn't work is important, better (more elegant and/or more resource friendly) solutions should not be overlooked. |
All times are GMT -5. The time now is 12:37 AM. |