- Open a text editor and create a new file.
- Copy and paste the below script into the file.
#!/bin/bash # Set the Java home directory JAVA_HOME=/path/to/java/home # Set the classpath and main class name CLASSPATH=/path/to/your/application.jar MAIN_CLASS=com.example.YourMainClass # Check if the program is already running if pgrep -f "$MAIN_CLASS" >/dev/null; then echo "Stopping the running instance of the program..." pkill -f "$MAIN_CLASS" sleep 5 # Wait for the program to stop gracefully fi # Run the Java program echo "Starting the program..." $JAVA_HOME/bin/java -cp $CLASSPATH $MAIN_CLASS
/path/to/java/homewith the actual path to your Java installation directory.
/path/to/your/application.jarwith the actual path to your compiled Java application’s JAR file.
com.example.YourMainClasswith the fully qualified name of your application’s main class.
- Save the file with a “.sh” extension, such as “run.sh”.
- Open a terminal and navigate to the directory where you saved the script.
- Make the script executable by running the command:
chmod +x run.sh
- Run the script by executing the command:
The script first checks if the program is already running using
pgrep. If a running instance is found, it stops the program using
pkill. After ensuring that the previous instance has stopped, it starts a new instance of the Java program using the specified Java home directory, classpath, and main class. Adjust the script as per your specific application’s requirements.