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

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.

| improve this answer | |
  • The script runs in my first PC perfectly when I execute the file using ./myfile.jar but when I execute in my other system it doesn't. Also the file permissions are set as a+x in both the cases. The main aim of me doing this is that I want to place my jar file in the PATH of the second system. If the shebang(header) line case was the reason then it should not have run in the first case as well. – user3751936 Mar 20 '15 at 9:40
  • Can you edit your question to include more information about the first case then? – AJefferiss Mar 20 '15 at 13:57
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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.