0

I am making a basic bash script. I am trying to get a PID value and store it in a variable. I got my script setup like this:

getPID = pgrep -f app.jar
kill -9 $getPID

And then, I realized that I was only printing pgrep -f app.jar onto the terminal. So I tried:

getPID = $(pgrep -f app.jar)
kill -9 $getPid

And still no luck, is there a way to get pgrep value and store it in the variable?
I came across multiple questions. And still no luck. I also tried this, not too sure what does $$ does.

pgrep -f app.jar
getPid = $$
kill $getPid

I am using Ubuntu 16.04 terminal.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
IntFooBar
  • 174
  • 3
  • 18
  • 1
    http://shellcheck.net/ will catch your problem here. (You can't have spaces around `=` in an assignment). – Charles Duffy Mar 13 '17 at 23:47
  • 1
    ... isn't the best idea using `SIGKILL` e.g. the `-9`. It really kills the process immediatelly and the program couldn't handle the correct termination... Just use `kill` without any number - the default is `-15` e.g. `SIGTERM`, and only if absolutely needed use the `-9`. – clt60 Mar 13 '17 at 23:48
  • Thanks jm666, yeah one of my colleagues was telling me to use ```SIGTERM``` instead of `SIGKILL`. Unless the program is not really closing properly, but thanks for the advice.. – IntFooBar Mar 14 '17 at 14:06

1 Answers1

4

$$ stands for the PID of the current shell, not the output of the previous command.

The correct way of capturing the output of pgrep into a variable is:

getPid=$(pgrep -f app.jar)  # note: no spaces around =
kill $getPid

To make it more resilient to pgrep finding no matching processes, do:

getPid=$(pgrep -f app.jar)
[[ $getPid ]] && kill $gitPid

Or you can use pkill to do this in one shot:

pkill -f app.jar

See also:

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140