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.”
Problem
You want to access the command-line arguments from your Scala shell script.
Solution
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:
#!/bin/sh exec scala "$0" "$@" !# args.foreach(println)
Save this code to a file named args.sh, make the file executable, and run it like this:
$ ./args.sh a b c a b c
Discussion
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:
#!/bin/sh
exec scala "$0" "$@"
!#
if (args.length != 2) {
Console.err.println("Usage: replacer <search> <replace>")
System.exit(1)
}
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:
$ ./args.sh Usage: replacer <search> <replace>
When it’s run with the correct number of arguments, the result looks like this:
$ ./args.sh 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:
#!/bin/sh
exec scala "$0" "$@"
!#
object Hello extends App {
println("Hello, world")
// if you want to access the command line args:
//args.foreach(println)
}
Hello.main(args)
Use the same syntax if you use a main method instead of an App object.
| this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |