[linux] Shell script to get the process ID on Linux

I want to write a shell script (.sh file) to get a given process id. What I'm trying to do here is once I get the process ID, I want to kill that process. I'm running on Ubuntu (Linux).

I was able to do it with a command like

ps -aux|grep ruby
kill -9 <pid>

but I'm not sure how to do it through a shell script.

This question is related to linux bash shell scripting

The answer is


Using grep on the results of ps is a bad idea in a script, since some proportion of the time it will also match the grep process you've just invoked. The command pgrep avoids this problem, so if you need to know the process ID, that's a better option. (Note that, of course, there may be many processes matched.)

However, in your example, you could just use the similar command pkill to kill all matching processes:

pkill ruby

Incidentally, you should be aware that using -9 is overkill (ho ho) in almost every case - there's some useful advice about that in the text of the "Useless Use of kill -9 form letter ":

No no no. Don't use kill -9.

It doesn't give the process a chance to cleanly:

  1. shut down socket connections
  2. clean up temp files
  3. inform its children that it is going away
  4. reset its terminal characteristics

and so on and so on and so on.

Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved!

Don't use kill -9. Don't bring out the combine harvester just to tidy up the flower pot.


This works in Cygwin but it should be effective in Linux as well.

ps -W | awk '/ruby/,NF=1' | xargs kill -f

or

ps -W | awk '$0~z,NF=1' z=ruby | xargs kill -f

Bash Pitfalls


If you already know the process then this will be useful:

PID=`ps -eaf | grep <process> | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
echo "killing $PID"
kill -9 $PID
fi

As a start there is no need to do a ps -aux | grep... The command pidof is far better to use. And almost never ever do kill -9 see here

to get the output from a command in bash, use something like

pid=$(pidof ruby)

or use pkill directly.


If you are going to use ps and grep then you should do it this way:

ps aux|grep r[u]by

Those square brackets will cause grep to skip the line for the grep command itself. So to use this in a script do:

output=`ps aux|grep r\[u\]by`
set -- $output
pid=$2
kill $pid
sleep 2
kill -9 $pid >/dev/null 2>&1

The backticks allow you to capture the output of a comand in a shell variable. The set -- parses the ps output into words, and $2 is the second word on the line which happens to be the pid. Then you send a TERM signal, wait a couple of seconds for ruby to to shut itself down, then kill it mercilessly if it still exists, but throw away any output because most of the time kill -9 will complain that the process is already dead.

I know that I have used this without the backslashes before the square brackets but just now I checked it on Ubuntu 12 and it seems to require them. This probably has something to do with bash's many options and the default config on different Linux distros. Hopefully the [ and ] will work anywhere but I no longer have access to the servers where I know that it worked without backslash so I cannot be sure.

One comment suggests grep-v and that is what I used to do, but then when I learned of the [] variant, I decided it was better to spawn one fewer process in the pipeline.


To kill the process in shell

getprocess=`ps -ef|grep servername`
#echo $getprocess
set $getprocess 
pid=$2
#echo $pid
kill -9 $pid

You can use the command killall:

$ killall ruby

Its pretty simple. Simply Run Any Program like this :- x= gedit & echo $! this will give you PID of this process. then do this kill -9 $x


option -v is very important. It can exclude a grep expression itself

e.g.

ps -w | grep sshd | grep -v grep | awk '{print $1}' to get sshd id

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to scripting

What does `set -x` do? Creating an array from a text file in Bash Windows batch - concatenate multiple text files into one Raise error in a Bash script How do I assign a null value to a variable in PowerShell? Difference between ${} and $() in Bash Using a batch to copy from network drive to C: or D: drive Check if a string matches a regex in Bash script How to run a script at a certain time on Linux? How to make an "alias" for a long path?