ihainan
ihainan

Reputation: 75

Executing find shell command in Scala using sys.process._ returns empty result

The find shell command below returns expected result on my system:

➜  ~ find /Users/ihainan/IdeaProjects/ScalaForTheImpatient -name "*.class"
/Users/ihainan/IdeaProjects/ScalaForTheImpatient/src/main/scala/character_8/character_8/Person.class
/Users/ihainan/IdeaProjects/ScalaForTheImpatient/src/main/scala/character_8/character_8/SecretAgent.class

But when I execute the following scala source code, it returns empty result on the same machine:

object Ex9 {
  def main(args: Array[String]): Unit = {
    import sys.process._
    val classFiles = s"""find /Users/ihainan/IdeaProjects/ScalaForTheImpatient -name "*.class" """ !!

    println(classFiles)
  }
}

Scala Version: 2.11.5, System: macOS Sierra, JRE Version: 1.8.0_91

Any ideas or suggestions?

Upvotes: 0

Views: 763

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31232

With postfix !! simple commands as echo "" will work

scala> "echo prayagupd" !!
res6: String =
"prayagupd
"

For find as well, you can achieve it (removing multiline string """ """ to string ""),

scala> "find /Users/ihainan/IdeaProjects/ScalaForTheImpatient -name *.class"!!

But it could be safer to use Seq("bash", "-c", "your command")

eg.

scala> import sys.process._
import sys.process._

scala> Seq("bash", "-c", "find /Users/ihainan/IdeaProjects/ScalaForTheImpatient -name *.class")!!

which is equivalent to running following bash command,

bash -c "find /Users/ihainan/IdeaProjects/ScalaForTheImpatient -name *.class"

Upvotes: 1

Related Questions