What’s the best way to use R scripts on the command line (terminal)?

Content of script.r:

#!/usr/bin/env Rscript

args = commandArgs(trailingOnly = TRUE)
message(sprintf("Hello %s", args[1L]))

The first line is the shebang line. It’s best practice to use /usr/bin/env Rscript instead of hard-coding the path to your R installation. Otherwise you risk your script breaking on other computers.

Next, make it executable (on the command line):

chmod +x script.r

Invocation from command line:

./script.r world
# Hello world

Leave a Comment