Manu Arora
Manu Arora

Reputation: 47

How to pass arguments to a java code using shell script

I am new to java & shell. I just have a vague idea about the procedure, which is like this-

  1. make an executable jar file
  2. make a shell script file & include this command in it

    java -jar /home/usr/mystuff/jarFile.jar arg1 arg2 arg3

  3. Now the doubts are-

    • There are so many files in my java eclipse project. Do I need to make an executable jar of only the file having main() method?
    • Will the arguments I supply using script be collected by the main function.
    • Whats the syntax of passing arguments in shell. Like $var or var or "var or something else

Upvotes: 1

Views: 14268

Answers (2)

anacron
anacron

Reputation: 6711

To run a jar file in this manner, java -jar /home/usr/mystuff/jarFile.jar. You must specify a Manifest file in your jar that has your main class. The manifest file must be placed in a META-INF folder in the root of your jar file.

For example, your MANIFEST.MF file should contain a similar entry:

Main-Class: com.example.MainClass

replace com.example.MainClass with the fully qualified name of your Main Class

The entire process listed above will be taken care by your IDE such as Eclipse when you create a "Runnable Jar" from your Java project > Export option > "Runnable Jar".


As for passing arguments from the Script to the Jar, you can pass values directly or by using a variable from the script.

For example, directly:

java -jar /home/usr/mystuff/jarFile.jar arg1 arg2 arg3

OR through shell variables:

var1="arg1"
var2="arg2"
var3="arg3"
java -jar /home/usr/mystuff/jarFile.jar $var1 $var2 $var3

Hope this helps!

Upvotes: 2

vegaasen
vegaasen

Reputation: 1032

1) You will have to be create an executable jar-file, yes (using Ant, Ivy, Maven or whatever)

2) Arguments is collected when you toss stuff to the jar file, jeah java -jar <jar-file> "Something goes in here" -DmyCoolVariable=hello

3) It depends, if you have variables in the script, then pass the variables - if you're using "static" stuff, then just pass the variable directly to the command. Like this: java -jar <jar-file> "$variables" -DmyCoolVariable=$someProperty

Upvotes: 0

Related Questions