Scala shell scripts and the command line: Prompting the user, and reading input

A great thing about Scala is that not only is it scalable, it was also created to help you work on small tasks, including being useful in shell scripts. This includes small shell script tasks like prompting a user interactively from a shell script, and reading their input.

You can prompt users with print commands like println and print, and you can read their input with all of these methods that are available on the Scala Console class:

  • readBoolean
  • readByte
  • readChar
  • readDouble
  • readFloat
  • readInt
  • readLong
  • readShort
  • readLine - lets you prompt a user and read their input as text

(There's also a readf method that lets you read formatted (structured) input, which I'll demonstrate in a future Scala tutorial.)

An example shell script

The Scala shell script shown here demonstrates several techniques you can use to (a) prompt users with your output and (b) read their input. I've added comments to the shell script, so I won't describe it beforehand:

#!/bin/sh
exec scala -savecompiled "$0" "$@"
!#

// write some text out to the user with Console.print
Console.println("Hello")

// Console is imported by default, so it's not really needed, just use println
println("World")

// readLine: lets you prompt the user and also read their command line input
val name = readLine("What's your name? ")

// readInt: read a simple Int
print("How old are you? ")
val age = readInt()

// you can also print output with printf
printf("Your name is %s and you are %d years old.\n", name, age)

// you can also use the Java Scanner class, if desired
val scanner = new java.util.Scanner(System.in)
print("Where do you live? ")
val input = scanner.nextLine()
print("You live in " + input)

I hope those comments provide enough explanation for how Scala command line input and output works. I encourage you to copy these commands into your own shell script, run it, and then see how everything works. (You'll quickly see that you'll want to add some error-checking to your script, especially the readInt() method.)

If the lines at the top of this shell script seem a little unusual, check out my previous Scala shell script tutorials, where those lines are explained:

I hope this Scala shell script example on prompting a user for input and then reading their input has been helpful. For many more Scala tutorials, see my Scala cookbook/recipes page.

More examples

For more examples on how to prompt users and read their input, see my “How to prompt users for input from Scala shell scripts” tutorial.