12.14. Redirecting the STDOUT and STDIN of External Commands

Problem

You want to redirect the standard output (STDOUT) and standard input (STDIN) when running external commands. For instance, you may want to redirect STDOUT to log the output of an external command to a file.

Solution

Use #> to redirect STDOUT, and #< to redirect STDIN.

When using #>, place it after your command and before the filename you want to write to, just like using > in Unix:

import sys.process._
import java.io.File

("ls -al" #> new File("files.txt")).!
("ps aux" #> new File("processes.txt")).!

You can also pipe commands together and then write the resulting output to a file:

("ps aux" #| "grep http" #> new File("http-processes.out")).!

Get the exit status from a command like this:

val status = ("cat /etc/passwd" #> new File("passwd.copy")).!
println(status)

You can also download a URL and write its contents to a file:

import sys.process._
import scala.language.postfixOps
import java.net.URL
import java.io.File

new URL("http://www.google.com") #> new File("Output.html") !

I don’t redirect STDIN too often, but this example shows one possible way to read the contents of the /etc/passwd file into a variable using #< and the Unix cat command:

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

val contents = ("cat" #< new File("/etc/passwd")).!!
println(contents)

Discussion

The #> and #< operators generally work like their equivalent > and < Unix commands, though you can also use them for other purposes, such as using #> to write ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.