Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala as a shell script: jars on the classpath

Tags:

jar

scala

You can run a scala script as a linux shell script:

#!/bin/sh
exec scala "$0" "$@"
!#

println("Hello")

In one such script I need to load classes from a group of jars (which happen to be in the same directory as the script). If this were the REPL I could use :jar, but that's not available in script mode.

I'm trying to set the -classpath parameter:

#!/bin/sh
exec scala -classpath '.:./*.jar' "$0" "$@"
!#

import javax.media.jai.{JAI, RenderedOp}

but the compiler just can't find the classes:

error: object media is not a member of package javax
import javax.media.jai.{JAI, RenderedOp}
             ^

How do I include these jars?

like image 998
Marcus Downing Avatar asked Nov 24 '11 09:11

Marcus Downing


2 Answers

exec scala -classpath ./*.jar $0 $@

will work

like image 115
viktortnk Avatar answered Sep 30 '22 21:09

viktortnk


For some reason, the glob (*.jar) wasn't working. I was able to get the script running by putting in all the libraries by hand:

#!/bin/sh
exec scala -cp lib/jai_codec.jar:lib/jai_core.jar:lib/mlibwrapper_jai.jar $0 $@
!#

import javax.media.jai.{JAI, RenderedOp}

I don't know why the glob isn't working though.

Note that in this case I don't have the . in the classpath because the script itself is provided as an argument. In many cases though you will need to include it:

exec scala -cp .:lib/jai_codec.jar:lib/jai_core.jar:lib/mlibwrapper_jai.jar $0 $@

Based on this helpful post, I have a script header that pulls in every jar in a lib folder, even if the script (or the folder it's in) are symlinks.

#!/bin/sh
L=`readlink -f $0`
L=`dirname $L`/lib
cp=`echo $L/*.jar|sed 's/ /:/g'`
/usr/bin/env scala -classpath $cp $0 $@
exit
!#
  • The first line turns the given script location $0 into its actual location on disk, expanding symlinks.
  • The second line removes the script name and adds /lib
  • The third line creates a cp variable with all the jars separated by :
  • The fourth line runs scala, wherever it may be.
  • The fifth line exits. This probably isn't necessary, but it makes me feel better.
like image 24
Marcus Downing Avatar answered Sep 30 '22 21:09

Marcus Downing