The examples below show two ways to run R code in a shell script. Both
examples will also define functions without executing them, if the scripts are
loaded to an interactive R session via the source() function.
The first example allows you to give arguments as you would to any other shell
script, but will not pass additional R-options to R (because Rscript gives
"--args" to R as one of the arguments).
The second example allows you to give additional R-options, but generates
(harmless) warning messages unless you give "--args" as one of the script
arguments. This version is best avoided unless you have special requirements.
prototype-Rscript.r
#!/usr/bin/env Rscript
# Prototype R script for use at command line in Linux, Mac OS X, UNIX
# References:
# Manual "A Introduction to R", available via help.start() from the R Console
# Appendix "B.1 Invoking R from the command line" in "A Inroduction to R",
showArguments <- function(argv) {
print(argv)
0
}
if ( ! interactive() ) {
# set some error return codes
SCRIPT_ERROR <- 10 # see documentation for quit()
SCRIPT_ARG_ERROR <- SCRIPT_ERROR + 1
# Define ARGV as script path concatenated to script arguments
ARGV <- commandArgs(FALSE) # start with all the arguments given to R
scriptPath <- sub("^--file=", "", grep("^--file=", ARGV, value=TRUE)) [[1]]
ARGV <- c(scriptPath, commandArgs(TRUE))
if (length(ARGV) < 2) {
cat(file=stderr(), sep="",
"Usage: ", ARGV[[1]], " [ options ] item ...\n",
" Do something with item\n",
" See script for details\n")
quit(save="no", status=SCRIPT_ARG_ERROR)
}
quit(save="no", status=showArguments(ARGV))
}
prototype-shellscript.r
#!/usr/bin/env R --slave --vanilla --quiet -f
# Prototype R script for use at command line in Linux, Mac OS X, UNIX
# References:
# Manual "A Introduction to R", available via help.start() from the R Console
# Appendix "B.1 Invoking R from the command line" in "A Inroduction to R",
showArguments <- function(argv) {
print(argv)
0
}
if ( ! interactive() ) {
# set some error return codes
SCRIPT_ERROR <- 10 # see documentation for quit()
SCRIPT_ARG_ERROR <- SCRIPT_ERROR + 1
# Define ARGV as the arguments given to this script (after argument “-f”)
ARGV <- commandArgs(FALSE) # start with all the arguments given to R
ARGV <- ARGV[(grep("-f", ARGV) [[1]] + 1):length(ARGV)]
if ( any(grepl("--args", ARGV) )) { # remove arguments intended only for R
ARGV <- c(ARGV[[1]], commandArgs(TRUE))
}
if (length(ARGV) < 2) {
cat(file=stderr(), sep="",
"Usage: ", ARGV[[1]], " [ R_options ] --args [ options ] item ...\n",
" Do something with item\n",
" See script for details\n")
quit(save="no", status=SCRIPT_ARG_ERROR)
}
quit(save="no", status=showArguments(ARGV))
}