Tim
Tim

Reputation: 4365

Shell script: running a java application and sending command-line args to it via the script?

This is for a class. I've never used shell scripting before, but the instructions are to write a script that runs my java program (which is already all set up to take in command line arguments (at least one arg, with an optional second one)). I'm supposed to be able to run it like this:

./script.sh arg1 arg2

But when I do, I get the following error (my java main class name is A1):

  Exception in thread "main" java.lang.NoClassDefFoundError: A1/class
  Caused by: java.lang.ClassNotFoundException: A1.class
    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:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
  Could not find the main class: A1.class.  Program will exit.

This is what my shell script looks like right now:

#!/bin/sh

java -Xmx1024m A1.class $@

Any help is appreciated.

Upvotes: 0

Views: 9865

Answers (2)

Dmitri
Dmitri

Reputation: 9157

You need to tell java where to look for your class (using -cp) - either in a directory or a .jar

To find the directory where the script is (as opposed to where it was launched from), you can use: $(dirname $0).

So, for example:

#!/bin/bash

JVM=java
JVM_OPTS="-Xmx1024m"

$JVM $JVM_OPTS -cp $(dirname $0)/myapp.jar A1 "$@"

It's a good idea to be explicit about the shell you want. Also note the quotes around $@, needed for escaped args.

Upvotes: 3

Nicolas Modrzyk
Nicolas Modrzyk

Reputation: 14197

Use the classpath flag when running java to tell the virtual machine where your A1.class file is located.

See the doc

Should be something like:

 java -classpath /myfolder A1 $@

Also, do not use the ".class" suffix when running the command.

Upvotes: 2

Related Questions