Wilson60
Wilson60

Reputation: 155

How to get rid of extra characters in linux process ID using shell script

I m trying to kill a process by its pid, and this is the script that I found from web.

PID=`ps -ef | grep myProcess | grep -v grep | awk '{print $2}'`  
echo -e Killing myProcess with pid: $PID..  

Output: Killing myProcesswith pid: 13275^M..

Does anyone know why is there a ^M , how do I get rid of that because the kill command failed to run :

**arguments must be process or job IDs**

I searched online but still got no idea how to overcome this.. Any help is appreciated!! Thanks!

Upvotes: 0

Views: 1825

Answers (4)

Rumple Stiltskin
Rumple Stiltskin

Reputation: 10405

You can just use :

PID=`pidof myProcess`

Upvotes: 0

flolo
flolo

Reputation: 15496

From what I see, you dont want to kill a process by PID, by its name. And you do it by getting the process PID and then try to kill it via PID. If you want to kill by name, use killall processname.

Upvotes: 0

kurumi
kurumi

Reputation: 25599

first, your syntax is wrong. Use $() to call a command and store its output to variable

PID=$(ps -ef | grep myProcess | grep -v grep | awk '{print $2}')

second, you can do this all in one awk statement without the need for extra grep processes.

ps -eo pid,args | awk '/myProces[s]/{cmd="kill  "$1;print cmd; }'

Upvotes: 1

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239684

From a quick read online, the print command to awk always appends a newline (which can sometimes be represented by Control-M, or ^M).

It would appear that printf would be a suitable alternative. Maybe:

PID=ps -ef | grep myProcess | grep -v grep | awk '{printf "%i",$2}'

Upvotes: 0

Related Questions