Shell Script to Start and Stop an Executable JAR in Linux Environment

3

2

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

Posted 2014-07-04T10:51:48.967

Reputation: 33

What distro? You're probably better off writing an init, upstart or systemd script – Journeyman Geek – 2014-07-04T10:55:14.300

Answers

3

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.

Hastur

Posted 2014-07-04T10:51:48.967

Reputation: 15 043

Thanks Hastur. Your logic worked for my problem. This is what I am expecting. – user3505567 – 2014-07-07T10:51:29.773

1

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)

ethanwu10

Posted 2014-07-04T10:51:48.967

Reputation: 931