Running Scala Code as a Stand-alone Script

Most operating systems support the shebang syntax to run arbitrary scripts. We can use that approach to run stand-alone files with Scala code in it. This eliminates the needs to explicitly invoke the scala command and works seamlessly as long as Scala is installed on the system.

Running as a Stand-alone Script on Unix-like Systems

On Unix-like systems, set the shebang preamble in the script like this:

FirstStep/hello.sh
 
#!/usr/bin/env scala
 
println(​"Hello "​ + args(0))

Make sure the file hello.sh has executable permission by typing chmod +x hello.sh. Then to run it, type the following command on the command line:

 
./hello.sh Buddy

Buddy is the argument that is passed to the script. Here’s the output ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.