I have a Scala application which needs to call the shell script by passing some arguments to it.
I followed the below answer and I am able to call the shell script from scala app without passing any arguments. But I have no idea how to pass the arguments.
Execute shell script from scala application
object ScalaShell {
def main(args : Array[String]): Unit = {
val output = Try("//Users//xxxxx//Scala-workbench//src//main//scala//HelloWorld.sh".!!) match {
case Success(value) =>
value
case Failure(exception) =>
s"Failed to run: " exception.getMessage
}
print(output)
}
}
HelloWorld.sh
#!/bin/sh
# This is a comment!
echo Hello World
Current Output:
Hello World
Expected Output:
Hello World, arg1 arg2 (where arg1 and arg2 were passed from scala)
CodePudding user response:
It is explained in great detail in Scala docs but my favorite way is this:
List("echo", "-e", "This \nis \na \ntest").!!
simply call the !!
method on a list where the first element is the script/command and the remaining elements are the args/options.
CodePudding user response:
In addition to @goosefand's answer, I have also added how to receive the arguments which is passed from scala in the shell script.
Scala:
object ScalaShell {
def main(args : Array[String]): Unit = {
val output = Try(Seq("//Users//xxxxx//Scala-workbench//src//main//scala//HelloWorld.sh", "arg1","arg2").!!) match {
case Success(value) =>
value
case Failure(exception) =>
s"Failed to run: " exception.getMessage
}
print(output)
}
}
Shell Script:
#!/bin/sh
echo Processing files $1 $2
Output:
Hello world arg1 arg2