How to Execute Shell Builtin from Scala

How to execute shell builtin from Scala

When strings are converted to a shell command, parameters are separated by space. The conventions you tried are shell conventions, so you'd need a shell to begin with to apply them.

If you want more control over what each parameter is, use a Seq[String] instead of a String, or one of the Process factories that amount to the same thing. For example:

Seq("sh", "-c", "ulimit -n").!!

Executing shell commands from Scala REPL

In REPL the :sh command allow you to introduce shell command:

Windows version:

scala> :sh cmd /C dir
res0: scala.tools.nsc.interpreter.ProcessResult = `cmd /C dir` (28 lines, exit 0)
scala> res0 foreach println

(unfortunately, there is no way to avoid the call to cmd \C before the shell command)

Unix-like version:

scala> :sh ls
res0: scala.tools.nsc.interpreter.ProcessResult = `cmd /C dir` (28 lines, exit 0)
scala> res0 foreach println

Update: Inspired by Daniel's answer, a little trick for windows user:

scala> implicit def stringToDosProcess(s: String) =
scala.sys.process.stringToProcess("cmd /C "+ s)
stringToDosProcess: (s: String)scala.sys.process.ProcessBuilder

scala> "dir".!

How to run a shell file in Apache Spark using scala

You must use sys.process._ package from Scala SDK and use DSL with !:

import sys.process._
val result = "ls -al".!

Or make same with scala.sys.process.Process:

import scala.sys.process._
Process("cat data.txt")!

Using scala.sys.process to invoke echo on Windows 7

You don't need to use echo at all. Instead, use the #< method of ProcessBuilder. Here is an example:

import java.io.ByteArrayInputStream
import scala.sys.process._

val data = "hello"
val is = new ByteArrayInputStream(data.getBytes)
"cat" #< is ! //complicated way to print hello

How to access shell script output when it is executed from inside a Java code?

Use a BufferedReader

Something like this:

BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
string line = "";
while ((line = reader.readLine()) != null)
System.out.println(line);
reader.Close();

What is the meaning of !# (bang-pound) in a sh / Bash shell script?

From the original documentation:

Script files may have an optional header that is ignored if present. There are two ways to format the header: either beginning with #! and ending with !#, or beginning with ::#! and ending with ::!#.

So the following code is just a header for a Scala script:

#!/usr/bin/env bash
exec scala "$0" "$@"
!#


Related Topics



Leave a reply



Submit