Sunday, January 13, 2008

Java Command Line apps under Linux

Your java command line apps cannot properly work under linux because of the spaces beetwen arguments.

For example the following bash script gives you wrong results:
#!/bin/sh
java -classpath $CLASSPATH eu.kostia.ejb.client.SendEmail $*


This is instead the right way:

#!/bin/sh

# concatenate args and use eval/exec to
# preserve spaces in paths, options and args
args=""
for arg in "$@" ; do
args="$args \"$arg\""
done

CLASSPATH=lib/commons-cli-1.1.jar:bin
cmd="java -classpath $CLASSPATH eu.kostia.ejb.client.SendEmail $args"

eval "exec $cmd"

As you can see, we concatenate first the arguments (enclosed in "...") and then we execute the command.

No comments: