【发布时间】:2018-06-15 13:52:18
【问题描述】:
我们如何将参数传递给 scala 脚本,就像我们将参数传递给 shell 脚本一样。
【问题讨论】:
我们如何将参数传递给 scala 脚本,就像我们将参数传递给 shell 脚本一样。
【问题讨论】:
像这样在顶部使用 bash 命令声明您的脚本
Test.scala
#!/bin/sh
exec scala "$0" "$@"
!#
object Test {
def main(args: Array[String]): Unit = {
println(s"args: ${args.mkString("[", ", ", "]")}")
}
}
有效
[Desktop] ./Test.scala "scala is awesome" "java8 has lambdas"
args: [scala is awesome, java8 has lambdas]
更多关于$0和$@的信息
0 Expands to the name of the shell or shell script.
This is set at shell initialization. If bash is
invoked with a file of commands, $0 is set to
the name of that file. If bash is started with
the -c option, then $0 is set to the first argument
after the string to be executed, if one is present.
Otherwise, it is set to the file name used to invoke
bash, as given by argument zero.
@ Expands to the positional parameters, starting from
one. When the expansion occurs within double quotes, each
parameter expands to a separate word. That is, "$@" is
equivalent to "$1", "$2" ... If the double-quoted
expansion occurs within a word, the expansion of the first
parameter is joined with the beginning part of the original
word, and the expansion of the last parameter is joined
with the last part of the original word. When there are no
positional parameters, "$@" and $@ expand to nothing
(i.e., they are removed).
欲了解更多信息,请访问:Command line args for Scala scripts
【讨论】:
./Test.scala。无需将其加载到 repl 中
就像你必须设置一个环境变量来传递 JVM 参数一样,你可以为你的参数设置一个环境变量。
set MYVARS=arg1 arg2 arg3
然后在你的 scala 脚本中:
val args = sys.env("MYVARS").split(" ").map(_.trim).toList
args.foreach { println }
【讨论】: