Programming Scala says:
Invoking scripts with scala is tedious when you use these scripts frequently. On Windows and Unix-like systems, you can create standalone Scala scripts that don’t require you to use the scala script-file-name invocation. For Unix-like systems, the following example demonstrates how to make an executable script. Remember that you have to make the permissions executable, e.g., chmod +x secho:
#!/bin/sh # src/main/scala/progscala2/toolslibs/secho exec scala "$0" "$@" !# print("You entered: ") args.toList foreach { s => printf("%s ", s) } println
Here is how you might use it:
$ secho Hello World You entered: Hello World
I was wondering what it means by
# src/main/scala/progscala2/toolslibs/secho
exec scala "$0" "$@"
!#
in sh
?
Can I make a Scala script standalone as
#!/path/to/scala
print("You entered: ")
args.toList foreach { s => printf("%s ", s) }
println
on Linux?
Thanks!
!#
mean? – Tim Mar 18 '20 at 11:30!#
is a shell feature not related to Scala http://alvinalexander.com/scala/scala-shell-script-example-exec-syntax. (2)${!#} means final positional parameter
http://tldp.org/LDP/abs/html/abs-guide.html, but here it is!#
, not sure if these two are related. (3) As youre reply says, there seems to be two ways writing a Scala script. Are both equivalent? when to use which, if you happen to know. – Tim Mar 18 '20 at 13:50scala
, not by the shell. (2) No, they are not related. The shell isn’t involved at all in handling!#
, it stops running before it gets to that line. (3) Given that the latter form works now, and is simpler, you might as well use that. Presumably older versions of Scala don’t support it, which is why the first form exists; but instead of looking at old docs, look at the current Scala docs, which refer to the simpler form. – Stephen Kitt Mar 18 '20 at 13:54!#
in scala language specification https://www.scala-lang.org/docu/files/doc/scala-documentation/ScalaReference.pdf – Tim Mar 18 '20 at 14:54#!/path/to/scala
as a comment? Why does#!/usr/bin/env scala
work then? (2) Is!#
used specifically for Scala or not specific to any language? (I don't find it in Scala language specification, and suspect it is not specific to any language.) – Tim Mar 18 '20 at 19:28/usr/bin/env
(or rather,/env
) is handled specifically. (2)!#
is specific to Scala, although since it’s the symmetric of!#
it’s possible other languages use a similar approach. – Stephen Kitt Mar 19 '20 at 08:18