2

Why does a .jar script run when I run it like java -jar myfile.jar, but it does not run when I execute it like ./myfile.jar

Krishna
  • 303

2 Answers2

5

When you run your jar using java -jar myfile.jar you're telling your shell to run the java command and passing it some arguments which java understands. However when you're running it using ./myfile.jar you're asking the shell to determine the interrupter to run it with, which it's unable to do.

The shell looks for the shebang line at the beginning to the script to known which application to run the script with, which is why you'll see shell scripts starting with:

#!/bin/bash

Or python scripts start with

#!/usr/bin/python

What you're telling the shell, basically, is to run the script using the application you find at /bin/bash or /usr/bin/python. In the case of your jar file, the shell is unable to find the shebang so it doesn't know how to execute the code.

In the past I've used wrapper scripts to execute Java applications, so something similar to:

#!/bin/bash

java -jar /path/to/myfile.jar

Then you just need to make that executable, using chmod and you can run it as you would any other shell script.

AJefferiss
  • 1,154
  • 9
  • 17
0

I had installed jdk using sudo apt-get install openjdk-7-jdk and jre using sudo apt-get install openjdk-7-jre but still I was facing this problem. I thought this might be due to the reason that my system was not able to find the java path. Finally when I installed oracle jdk7 installer using the following commands, then I was able to run the .jar file using ./myfile.jar command. I used the following commands to install it:

sudo add-apt-repository ppa:webupd8team/java

sudo apt-get update

sudo apt-get install oracle-jdk7-installer