How to run an R script from the command line

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.

Steps to run an R script from the command line:

  1. Create a dedicated directory for the R script and its input file.
    $ mkdir r-script-example
  2. Enter the new working directory as the shell's relative-path base.
    $ cd r-script-example
  3. Add the sample sales records to sales.csv.
    sales.csv
    item,amount
    notebook,12.50
    pen,7.25
    lamp,25.00
  4. Add the positional argument contract to summary.R.
    summary.R
    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.

  5. Append the missing-input check to summary.R.
    summary.R
    if (!file.exists(input_path)) {
      stop(sprintf("Input file does not exist: %s", input_path), call. = FALSE)
    }
  6. Append the CSV reader and required-column check to summary.R.
    summary.R
    sales <- read.csv(input_path)
     
    if (!"amount" %in% names(sales)) {
      stop("Input CSV must contain an amount column", call. = FALSE)
    }
  7. Append the total calculation and report writer to summary.R.
    summary.R
    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
    ))
  8. Compare the completed summary.R script with this consolidated file.
    summary.R
    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
    ))
  9. Run summary.R with the input and output paths.
    $ Rscript summary.R sales.csv total.txt
    Wrote total.txt (3 rows, total 44.75)
  10. Confirm that the successful R process returned status zero.
    $ printf 'success_status=%s\n' "$?"
    success_status=0

    A zero status lets a scheduler or CI job continue after the report is written.

  11. Inspect the report written by the script.
    $ cat total.txt
    rows=3
    total=44.75
  12. Exercise the missing-input path with a nonexistent CSV file.
    $ Rscript summary.R missing.csv failed.txt
    Error: Input file does not exist: missing.csv
    Execution halted
  13. Confirm that the failed R process returned status one.
    $ printf 'failure_status=%s\n' "$?"
    failure_status=1

    The nonzero status prevents calling automation from treating a missing input as a completed report.

  14. Run summary.R again with the valid input after the failed invocation.
    $ Rscript summary.R sales.csv total.txt
    Wrote total.txt (3 rows, total 44.75)
  15. Confirm that the recovered run returned status zero.
    $ printf 'success_status=%s\n' "$?"
    success_status=0