-1

When I run a command in a Linux script that starts a process, I'd like to capture the process number for that command in a variable for later use (i.e. to kill it later on).

Here's the command that starts the process

./run external

Would it be something like:

./run external/ pid=$!?

Manually I do: ps -ef|grep run, which gives me a process ID and then I can kill it manually but I want to capture the PID in the script in a variable so I can say: kill $variable (that has the PID value in it).

Ideas?

asontu
  • 4,548
  • 1
  • 21
  • 29

2 Answers2

2

You can extend your manual method to make it work automatically:

pid=$(ps -ef | grep run | grep -v grep | awk '{print $2}')
Dan
  • 10,614
  • 5
  • 24
  • 35
  • Ugh. `pid=$(ps -ef | awk '/[r]un/ { print $2 }'` – tripleee Feb 26 '15 at 16:48
  • The problem with ps approaches is if multiple processes are running you may kill the wrong one. – ComputerDruid Feb 26 '15 at 20:00
  • since the awk process also gets found, I used an anchor to get 1 hit only on "someapplication" ` pid=$(ps -ef | awk '/someappliation$/ { print $2 }') ` many thanks to @tripleee for the hint here. –  Oct 03 '19 at 11:47
2

A task run in the background has its PID in $!

$ sleep 30 &
[1] 21493
$ echo $!
21493
$ ps -ef | grep sleep
dbj      21493 21414  0 11:42 pts/26   00:00:00 sleep 30

So you should be able to capture that value and kill that PID later.

ComputerDruid
  • 16,897
  • 1
  • 19
  • 28
  • The OP does not start a background process via the shell. Instead the command backgrounds itself. The shell cannot output the background process id via `$!` in this case because it does not have that information. – Michael Jaros Feb 26 '15 at 19:44
  • Most processes that background themselves have an option to not do that, which makes later killing them much simpler. – ComputerDruid Feb 26 '15 at 19:59