Shorter Scala Script header
Asked Answered
M

2

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.

Macaroon answered 1/10, 2011 at 12:13 Comment(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.Usurer
J
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!
Jahvist answered 1/10, 2011 at 13:20 Comment(5)
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/.Nucellus
@javadba - seems you somehow grabbed the wrong interpreter. Can you paste your .scala file somewhere?Jahvist
@javadba - what happens if you do /usr/local/bin/scala /shared/stest.scala?Jahvist
2015 now: and in 2.11 the one liner "#!/usr/bin/env scala" is now working.Gaylordgaylussac
@javadba - Yes, that's true. Thanks for the comment, I updated the answer.Jahvist
B
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
Bannock answered 1/10, 2011 at 15:11 Comment(4)
@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.Bannock
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 !#Gaylordgaylussac
@javadba I've added more information. The pull request was accepted. I`ve complemented the answer with the syntax it allows.Bannock
2015 now and in scala 2.11 this one liner is working GREAT.Gaylordgaylussac

© 2022 - 2024 — McMap. All rights reserved.