0

I'm trying to get my .sh file to run a Java program for a specific amount of time.


Here's my .sh file:

#Runs Java Repeatedly.
#Reset directory
cd
#Go until src
cd Desktop/Lin\ Lab/Java\ Workspace/SandBubbler/src/

for((i = 0; i < 10; i++))
do
    java testerPackage.BubblerSimulation
    #kill process after x amount of seconds.
done

I'm new to Unix/Linux (I started learning it yesterday) so please explain it in a simple way. Thanks!

1 Answers1

0
for ((i=0; i<10; i++)); do
    java testerPackage.BubblerSimulation &
    javapid=$!
    sleep 10
    kill -TERM $javapid
    wait $javapid
done

Using & after a command runs it in the background and continues on to the next command. We then capture the pid (process ID) of the last backgrounded command which is in the special variable value of $!.

sleep is a command which will simply pause for the specified number of seconds.

We then use the kill command with the captured pid to tell the java process to terminate itself, and wait for the cleanup to complete before iterating into the next run of the loop.

DopeGhoti
  • 76,081