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
Try littler. littler
provides hash-bang (i.e. script starting with #!/some/path) capability for GNU R, as well as simple command-line and piping use.
Miguel Sanchez's response is the way it should be. The other way executing Rscript could be 'env' command to run the system wide RScript.
#!/usr/bin/env Rscript