0

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.

1

2 Answers 2

3

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.

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

Comments

1

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.

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.