1

I want to execute a jar file using java -jar command from a bash script. At the same time I'm passing few parameters which I can access in my main method, using args[].

I'm able to do this without any issues if I try,

java -jar org.sample.jar localhost 8080

but I want to make these parameters configurable through few variables.

Eg:-

HOST=localhost
PORT=8080

When I try to use above variables like following, bash script fails silently.

java -jar org.sample.jar $HOST $PORT

I also tried using "$HOST" but without any luck. What am I doing wrong here?

UPDATE

I was using cygwin to execute/debug my bash script. Once I execute the same script using git bash it works.

udarakr
  • 536
  • 2
  • 6
  • 18

1 Answers1

4

You should wrap this in a bash scripts and using bash parameters.

Say you will have a script file sample.sh.

in sample.sh, it contains only one line, which is java -jar org.sample.jar "$@"

Then execute your jar file by bash sample.sh -Host hostname -port 8080

Here is a post about how to do this.

UPDATE

To use variables in your bash script, your script will look like this:

Host="localhost"
Port=8080

java -jar org.sample.jar $Host $Port

I'm using Eclipse and I only wrote one class which has a main method and prints all the arguments. Then I used Eclipse to export a jar file and then used this solution and it worked.

Community
  • 1
  • 1
lkq
  • 2,326
  • 1
  • 12
  • 22
  • Yes, but my requirement is to use variables which exist within my bash script. I don't want to execute my bash script passing arguments. – udarakr Apr 02 '16 at 22:14
  • I don't see any difference, because you really don't need to use "" to define the host variable. As far as I know quotations required only if you have a white-space Eg:- local host – udarakr Apr 02 '16 at 22:32
  • @udarakr Then check if your main method handles the parameters properly, since I've tested it and it had no problem. – lkq Apr 02 '16 at 22:35
  • I'm using maven-jar plugin, but that should not have any effect since I can execute my jar using "java -jar org.sample.jar localhost 8080" – udarakr Apr 02 '16 at 22:35
  • If there is an issue within my java class it should fail for both cases. – udarakr Apr 02 '16 at 22:36
  • @udarakr Okay, then I'm not sure what is happening. I used this way and never had any issue. – lkq Apr 02 '16 at 22:45
  • found the problem :) I was using cygwin on windows to execute/debug my bash script. Once I execute the same script using git bash it works. – udarakr Apr 02 '16 at 22:55