Ubuntu – Difference between sh file.sh and file.sh

bashjava

I have two questions :

  1. What is the difference between executing sh filename.sh and filename.sh?
  2. How can I make both of them giving me the same output ?

I'm asking this question as right now I'm facing a problem. I'm trying to run a Java + SWT application from terminal.

When I do filename.sh, it gives me the desired output.
But when I do sh filename.sh or bash filename.sh, it throws me an error :

Exception in thread "main" java.lang.NoClassDefFoundError: MainForm/java
Caused by: java.lang.ClassNotFoundException: MainForm.java
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: MainForm.java.  Program will exit.

I know this question is already asked here but I'm still not clear about it.

I have gone through the following links :

What is the difference between ./ and sh to run a script?

Can scripts run even when they are not set as executable?

Can anyone help me with this?

Best Answer

The script probably knows which shell it should be running in. The first line might be something like

#!/bin/bash

If you run it with sh, the first line (a.k.a. shebang) is ignored. A different shell tries to run the script, but does not understand it - it is like running Java code in Pascal. If you run it with the right shell, it should behave identically:

/bin/bash script.sh