Reputation: 9892
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.
Upvotes: 1
Views: 4024
Reputation: 2599
Assuming Linux is used, one can start with a simple "pwd"!
, which will display the working directory, and then invoke the shell script using relative or absolute path. E.g.:
import sys.process._
object POC extends App{
val path = "pwd".!!.trim
println(path)
s"$path/src/main/bin/test.sh".!
"src/main/bin/test.sh".!
}
returns:
/home/user/temp/scala-shell-script
Hello shell
Hello shell
BTW, shell scripts usually have #!/bin/sh
(not #!/bin
) in the shebang line:
#!/bin/sh
echo "Hello shell"
Upvotes: 2