HOME BLOG

Archive for the ‘Unix’ Category

How to get process id of last executed background process in Shell script

Posted on: August 10th, 2021 by Olu No Comments

Hi folks,

In this short post I will describe how to get the process id of the last process that was executed in the background.

You do that using the symbol $!

E.g. If you run the commands:

date &
echo $!

you will get an id like 12345 corresponding of the process id for the date command you ran in the background previously.

The process id of the last run background process could be very useful if you want to do things like killing the process when a certain condition is meant. For example, when deploying multicontainer pods in Kubernetes using the sidecar pattern, you may want to terminate the sidecar container once the main container’s process finishes. One way to do this is in the sidecar is to start the sidecar process in the background, fetch its process id, wait for a trigger file which will be written by main container to signal process completion, then kill the sidecar process once the trigger file is found.

See the article How to terminate a side-car container in Kubernetes Job [1] for details.

That’s all for now. Happy software development.

 

Reference

1. How to terminate a side-car container in Kubernetes Job https://cotton-ori.medium.com/how-to-terminate-a-side-car-container-in-kubernetes-job-2468f435ca99

2. Does $! mean something in shell scripting. Stackoverflow. https://stackoverflow.com/questions/18462916/does-mean-something-in-shell-scripting