Open In App

How to Execute OS Commands in Scala?

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Scala is a versatile programming language. It offers smooth approaches to running OS instructions, whether or not you want to deal with documents, automate system operations, or communicate with external gear. This article focuses on discussing ways to execute OS commands in Scala.

Prerequisites

  1. Installation of Scala: Verify that Scala is established on your PC. Scala may be downloaded and installed from its authentic internet site, or in case your running system has one, you may make use of a package supervisor.
  2. Basic Scala Knowledge: Learn the basics of Scala programming, such as variables, functions, and manipulate systems. This tutorial assumes a primary knowledge of syntax and semantics in Scala.

Implementation

The scala.Sys.Method bundle comes with Scala and affords a simple way to run OS instructions. With the help of this package, you can manipulate input streams, execute instructions synchronously or asynchronously, etc.

Use the ! method to execute the command and get its exit status.

Use the !! method to execute the command and get its output.

Executing a Simple Command

Below is the Scala program to execute ls command:

Scala
import scala.sys.process._

object ExecuteOSCommand {
  def main(args: Array[String]): Unit = {
    val result = "ls".!!
    println(result)
  }
}

Output:

11

Executing a Command with Arguments

Below is the Scala program to execute ls-l command:

Scala
import scala.sys.process._

object ExecuteOSCommand {
  def main(args: Array[String]): Unit = {
    val result = Seq("ls", "-l").!!
    println(result)
  }
}

Output:

12

Executing a Command with Capturing its Exit Status

Below is the Scala program to execute ls-l command with exit code:

Scala
import scala.sys.process._
object ExecuteOSCommand {
def main(args: Array[String]): Unit = 
  {
    val result = Process("ls -l").!
    println(s"Exit code: $result")
  }
} 

Output:

13

Conclusion

The scala.Sys.Manner package makes it easy to execute OS instructions in Scala. Your Scala packages can without problems include OS command execution in case you use the approach defined in this guide. Scala offers you the equipment you need to do jobs fast and continually, whether or not you are managing documents, automating gadget approaches, or integrating with external technology. To fully make use of OS command execution in Scala, pass over the abilties offered by means of the scala.Sys.Process bundle and test with various instructions.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads