Interactive R sessions keep objects, prompts, and working state in one place, while automated jobs start without that context. A command-line script makes its inputs explicit so the same calculation can run from a terminal, scheduler, CI runner, or another program.
The Rscript front end accepts a script file followed by arguments for that script. Inside R, commandArgs(trailingOnly = TRUE) returns those trailing values, which lets the script treat the first value as an input path and the second as an output path.
Relative paths resolve from the shell's working directory, not from the directory that contains the script. Explicit argument and input checks keep a bad invocation from writing a misleading report, and the process status tells calling automation whether the run succeeded.
$ mkdir r-script-example
$ cd r-script-example
item,amount notebook,12.50 pen,7.25 lamp,25.00
args <- commandArgs(trailingOnly = TRUE) if (length(args) != 2) { stop("Usage: Rscript summary.R INPUT.csv OUTPUT.txt", call. = FALSE) } input_path <- args[[1]] output_path <- args[[2]]
The script requires exactly two values after its filename: the source CSV and the destination report.
if (!file.exists(input_path)) { stop(sprintf("Input file does not exist: %s", input_path), call. = FALSE) }
args <- commandArgs(trailingOnly = TRUE) if (length(args) != 2) { stop("Usage: Rscript summary.R INPUT.csv OUTPUT.txt", call. = FALSE) } input_path <- args[[1]] output_path <- args[[2]] if (!file.exists(input_path)) { stop(sprintf("Input file does not exist: %s", input_path), call. = FALSE) } sales <- read.csv(input_path) if (!"amount" %in% names(sales)) { stop("Input CSV must contain an amount column", call. = FALSE) } total <- sum(sales$amount, na.rm = TRUE) report <- c( sprintf("rows=%d", nrow(sales)), sprintf("total=%.2f", total) ) writeLines(report, output_path) cat(sprintf( "Wrote %s (%d rows, total %.2f)\n", output_path, nrow(sales), total ))
$ Rscript summary.R sales.csv total.txt Wrote total.txt (3 rows, total 44.75)
$ printf 'success_status=%s\n' "$?" success_status=0
A zero status lets a scheduler or CI job continue after the report is written.
$ cat total.txt rows=3 total=44.75
$ Rscript summary.R missing.csv failed.txt Error: Input file does not exist: missing.csv Execution halted
$ printf 'failure_status=%s\n' "$?" failure_status=1
The nonzero status prevents calling automation from treating a missing input as a completed report.
$ Rscript summary.R sales.csv total.txt Wrote total.txt (3 rows, total 44.75)
$ printf 'success_status=%s\n' "$?" success_status=0