I'm new to Scala programming. I have one .sh file
. I want to run this file using Scala. I have tried solutions provided in the below link. But those are not working for me.
Execute shell script from scala application
I have tried simple echo command in scala REPL and it's working fine. But when I used the same line of code in Scala program I am getting java.io.IOException
like below.
Exception in thread "main" java.io.IOException: Cannot run program "echo": CreateProcess error=2, The system cannot find the file specified
And my sample code looks like below
import java.io._
import sys.process._
object POC {
def main( args: Array[String]) {
val p = "echo 'hello world'".!!
println("############################################# "+ p)
}
}
EDIT:
As per the Tom's response, I have modified above code like below and it's working fine now and getting Hello world
in console.
import java.io._
import sys.process._
object POC {
def main( args: Array[String]) {
val p = Seq("echo", "hello world")
val os = sys.props("os.name").toLowerCase
val panderToWindows = os match {
case x if x contains "windows" => Seq("cmd", "/C") ++ command
case _ => command
}
panderToWindows.!
}
}
Now my exact issue is to execute my script.sh file. I have directory like below.
src
- bin
- script.sh
- scala
- POC.scala
script.sh code:
#!/bin
echo "Hello world"
And my POC.scala consists below code.
import java.io._
import sys.process._
object POC {
def main( args: Array[String]) {
val command = Seq("/bin/script.sh")
val os = sys.props("os.name").toLowerCase
val panderToWindows = os match {
case x if x contains "windows" => Seq("cmd", "/C") ++ command
case _ => command
}
panderToWindows.!
}
}
I didn't get any console output after executing above code. Please let me know if I missed anything. Thanks.