urug
urug

Reputation: 415

executing unix commands from scala script

I am not clear on best practice to execute unix commands from my scala based script.

A typical scala script is here

#!/bin/sh
exec scala "$0" "$0" "$@"
!#

println("args length is ", args.length)

### want to list all files in the underlying folder
val resultSet = "ls -la"????

I checked a number of posts but nothing clearly outlines a working script which can execute a unix command from scala script and perform some transformations.

Upvotes: 0

Views: 1354

Answers (2)

jwvh
jwvh

Reputation: 51271

Here's a simple script to get you started.

#!/usr/bin/env scala
import scala.sys.process._

// args is auto-populated
println("arg len = " + args.length)

// get listing of current files
val files: Array[String] = "ls -a".!!.split("\n")
println("5th fiile is " + files(4))

System.exit(0)

Study the process package of the Standard Library for more on capturing process output, process exit status, pipelining, etc.

Upvotes: 1

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

import scala.sys.process._ and use the ! and !! to execute the linux commands

scala> import scala.sys.process._
scala> "ls -la" !
scala> "ls -la" !!

You can do this in the scala script as well

! returns exit code of the command after executing

!! returns the output of the command after executing

Parse the output of the "ls -la" !! and get the files in the current dir.

Upvotes: 3

Related Questions