12.13. Building a Pipeline of Commands

Problem

You want to execute a series of external commands, redirecting the output from one command to the input of another command, i.e., you want to pipe the commands together.

Solution

Use the #| method to pipe the output from one command into the input stream of another command. When doing this, use ! at the end of the pipeline if you want the exit code of the pipeline, or !! if you want the output from the pipeline.

The !! approach is shown in the following example where the output from the ps command is piped as the input to the wc command:

import sys.process._
val numProcs = ("ps auxw" #| "wc -l").!!.trim
println(s"#procs = $numProcs")

Because the output from the ps command is piped into a line count command (wc -l), that code prints the number of processes running on a Unix system. The following command creates a list of all Java processes running on the current system:

val javaProcs = ("ps auxw" #| "grep java").!!.trim

There are other ways to write these commands, but because I usually end up trimming the result I get back from commands, I find this syntax to be the most readable approach.

Discussion

If you come from a Unix background, the #| command is easy to remember because it’s just like the Unix pipe symbol, but preceded by a # character (#|). In fact, with the exception of the ### operator (which is used instead of the Unix ; symbol), the entire library is consistent with the equivalent Unix commands.

Note that attempting to pipe commands ...

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.