9

It's possible to write shell scripts in Scala by starting a text file with:

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

To ease script creation, I would like to write an executable called scalash (perhaps a BASH script) allowing to shorten Scala script header to just one line:

#!/bin/scalash

Is it possible ? Extra points if I can pass optional parameters to scalash, for instance to add classpath dependencies.

1
  • Not sure here, but I think the "one parameter only" restriction of the shebang line comes from the OS; don't know, whether there is something you could do about that. Commented Oct 1, 2011 at 13:06

2 Answers 2

17

In Scala 2.11, you can do it as follows (exactly as with most other languages):

#!/usr/bin/env scala
println(args.mkString(" "))

In Scala 2.9.0.1, you can simply create the following script:

test.scala

#!/usr/bin/scala
!#
println(args.mkString(" "))

and make it executable. (change the first line to path to your executable)

Usage:

# ./test.scala Hello world!
Hello world!
Sign up to request clarification or add additional context in comments.

5 Comments

You can even make the first line #!/usr/bin/env scala. Should work as long as the scala binary is in PATH, not necessarily in /usr/bin/.
@javadba - seems you somehow grabbed the wrong interpreter. Can you paste your .scala file somewhere?
@javadba - what happens if you do /usr/local/bin/scala /shared/stest.scala?
2015 now: and in 2.11 the one liner "#!/usr/bin/env scala" is now working.
@javadba - Yes, that's true. Thanks for the comment, I updated the answer.
8

See this pull request (was this). There's no issue associated with it -- if you feel like it, you could open an issue and comment on the pull request.

You can also use SBT to start the scripts. See information about scalas here.

EDIT

The pull request was accepted, so this should work:

#!/usr/bin/env /path/to/scala
etc

4 Comments

@javadba Thanks. That link pointed to an old mirror of the svn repository, which was replaced by the current git repository. I've fixed that, and also the other link which has since moved as well.
I hope the pull gets accepted. The present situation means debuggers are confused - the line numbers are off by the number of lines between #! and !#
@javadba I've added more information. The pull request was accepted. I`ve complemented the answer with the syntax it allows.
2015 now and in scala 2.11 this one liner is working GREAT.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.