How to access command-line arguments in Scala shell scripts

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 14.11, “How to access command-line arguments in a Scala shell script.”


You want to access the command-line arguments from your Scala shell script.


Use the same script syntax as shown in Recipe 14.8, “How to Generate Scala Documentation with scaladoc”, and then access the command-line arguments using the args variable, which is a List[String] that is implicitly made available:

exec scala "$0" "$@"


Save this code to a file named, make the file executable, and run it like this:

$ ./ a b c


Because the implicit field args is a List[String], you can perform all the usual operations on it, including getting its size, and accessing elements with the usual syntax.

In a more “real-world” example, you’ll check for the number of command-line arguments, and then assign those arguments to values. This is demonstrated in the following script:

exec scala "$0" "$@"
if (args.length != 2) {
    Console.err.println("Usage: replacer <search> <replace>")

val searchPattern = args(0)
val replacePattern = args(1)
println(s"Replacing $searchPattern with $replacePattern ...")

// more code here ...

When this script is run from the command line without arguments, the result looks like this:

$ ./
Usage: replacer <search> <replace>

When it’s run with the correct number of arguments, the result looks like this:

$ ./ foo bar
Replacing foo with bar ...

Using the App trait

If you decide to use the App trait in your script, make sure you pass the command-line arguments to your App object, as shown in the Hello.main(args) line in this example:

exec scala "$0" "$@"
object Hello extends App {
    println("Hello, world")
    // if you want to access the command line args:


Use the same syntax if you use a main method instead of an App object.