1
#!/usr/bin/env bash
gnome-terminal --title='Restarter' -- bash -c \
"
while true
do
    ./instanceOfJavaProcess #opens another window
    ./secondInstanceOfJavaProcess #opens another window
    sleep 5
    echo Restarting!
    pkill -f 'java.*JavaProcess'
done;
exec bash
"

I am trying to use a bash script to restart a specific Java process every 24 hours.

The problem I have is that the pkill command seems to be killing the Restarter script as well. The weird thing is that this only happens when I run this script under the bash command. If I copy and paste the entire while true loop, the script does not terminate itself. I have been trying for hours trying to get this to work, but I really do not understand why the behavior of the script is different while its under the bash command than when its being executed by the bash command than just running it in a bash terminal.

I even put the while loop in a separate script (Temp.bash), then in the Restart script, I changed the gnome-terminal line to: gnome-terminal --title='Restarter' -- Temp.bash This worked as expected too. I am not a fan of this solution, but now I want to understand why this issue is happening. I would like to use the first solution and condense the entire script into one file as well.

Any insight? Thanks!

  • 1
    This is presumably because "java.*JavaProcess" occurs in the arguments to `bash -c`, so `pkill -f` matches it and kills that process (see ["Prevent process from killing itself using pkill"](https://stackoverflow.com/questions/15740481)). In this case, probably the easiest fix is to use a pattern that doesn't match itself, like `pkill -f '[j]ava.*JavaProcess'` (where the `[]` prevents a self-match; see [this answer about a similar problem](https://stackoverflow.com/questions/3510673/find-and-kill-a-process-in-one-line-using-bash-and-regex/3510850#3510850)). – Gordon Davisson Jun 17 '23 at 20:25
  • 1
    That did it! Thank you!! You are the greatest! – Mariocraft95 Jun 17 '23 at 20:35

0 Answers0