Shell Script to Start and Stop an Executable JAR in Linux Environment
Solution 1
This is the simple version: you can write a little script as the one below (save it as MyStart.sh)
#!/bin/bash
java -jar executable.jar & # You send it in background
MyPID=$! # You sign it's PID
echo $MyPID # You print to terminal
echo "kill $MyPID" > MyStop.sh # Write the the command kill pid in MyStop.sh
When you execute this script with /bin/bash MyStart.sh
, it will print the PID of that process on the screen.
Else you can change the attribute to MyStart.sh (chmod u+x MyStart.sh
) and run it simply with ./MyStart.sh
.
To stop the process you can write by command line kill 1234
where 1234 is the PID answered by the script, or /bin/bash MyStop.sh
Remember to delete the script MyStop.sh after that you use it.
Solution 2
You don't need to run a separate script to stop the task.
Borrowing from Hastur's script:
#!/bin/bash
java -jar executable.jar & # Send it to the background
MyPID=$! # Record PID
echo $MyPID # Print to terminal
# Do stuff
kill $MyPID # kill PID (can happen later in script as well)
user3505567
Updated on September 18, 2022Comments
-
user3505567 over 1 year
I have to write a start and stop script for an executable jar (e.g., executable.jar).
How to do it using shell scripting?
I got success to do it for Windows environment with .bat file. But not able to manage to write a shell script for same.
-
user3505567 almost 10 yearsThanks Hastur. Your logic worked for my problem. This is what I am expecting.