Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a shell script to run a Java program on Linux

Tags:

java

linux

shell

I have created a java program which syncs the contents of two directories. The program takes the location of the two directories as arguments the proceeds to sync them, the sync information is them stored in a JSON formatted file inside each directory. I have one referenced library json-simple-1.1.1.jar

I'm running this from eclipse on windows and everything is working correctly. I want to create a shell script so that I can run this on a Linux terminal by typing sync dir1 dir2 where sync is my java program and dir1 and dir2 are the paths to the directories to synchronize from the current directory.

I'm very new to shell scripts and Linux and unsure whether this is easy to do or will take me all day.

like image 940
M0rty Avatar asked Sep 27 '15 02:09

M0rty


People also ask

Can we call Java code from shell script?

You can't execute an arbitrary method directly from a shell script, you'll need to have that method exposed externally in some way. The simplest way of course is to write a main method that directly invokes the code you want to test.


2 Answers

create a file named "sync" in /usr/bin containing the following:

java -jar {PATH TO JARFILE} $1 $2

Replace {PATH TO JARFILE} with the path to the jarfile

Make the file executable by typing chmod +x sync while in /usr/bin

like image 67
DutChen18 Avatar answered Oct 04 '22 09:10

DutChen18


you can create a shell with name say "run.sh" (note .sh extension which tell it is a shell script) and copy it in /usr/local/bin directory.

1.Script (run.sh)

#!/bin/sh

arg1=$1
arg2=$2

##directory where jar file is located    
dir=/directory-path/to/jar-file/

##jar file name
jar_name=json-simple-1.1.1.jar

## Permform some validation on input arguments, one example below
if [ -z "$1" ] || [ -z "$2" ]; then
        echo "Missing arguments, exiting.."
        echo "Usage : $0 arg1 arg2"
        exit 1
fi

java -jar $dir/$jar_name arg1 arg2
  1. copy the script in /usr/local/bin

    cp run.sh /usr/local/bin

  2. Give execute permission to the script

    chmod u+x /usr/local/bin/test.sh

  3. now you can type just word run or run.sh on command line : shell will auto-complete the script name and also it can executed by pressing enter key.

like image 45
spectre007 Avatar answered Oct 04 '22 08:10

spectre007