0

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)

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.