1

How can we pass arguments to scala script like how we pass arguments to a shell script.

2 Answers 2

1

Much like you have to set an environment variable to pass JVM arguments, you can set an environment variable for your arguments.

set MYVARS=arg1 arg2 arg3

Then in your scala script:

val args = sys.env("MYVARS").split(" ").map(_.trim).toList
args.foreach { println }
Sign up to request clarification or add additional context in comments.

Comments

0

Declare your script with bash command on top like this

Test.scala

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

object Test {
  def main(args: Array[String]): Unit = {
    println(s"args: ${args.mkString("[", ", ", "]")}")
  }
}

It works

[Desktop] ./Test.scala "scala is awesome" "java8 has lambdas"
args: [scala is awesome, java8 has lambdas]

More info regarding $0 and $@

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).

for more info visit: Command line args for Scala scripts

4 Comments

Thanks for swift reply, for some reason I'm not able to get. never mind. Currently I'm working on scala shell means scala>:load test.scala so how to pass parameters here? sorry I'm new to scala
@KPM scala scripts are run on command line like bash scripts. You must not load in into repl. Check in the answer, I have used ./Test.scala on the command line. No need to load it into repl
I'm getting exec. scala. not found. could you please hint me ?
@KPM Install scala first from here scala-lang.org/download

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.