Skip to content

Instantly share code, notes, and snippets.

@HenrikBengtsson
Last active December 19, 2017 21:11
Show Gist options
  • Save HenrikBengtsson/27314c2b5e11105c7ea4dcec51036794 to your computer and use it in GitHub Desktop.
Save HenrikBengtsson/27314c2b5e11105c7ea4dcec51036794 to your computer and use it in GitHub Desktop.
Shell/batch scripts calling R

Example of using myscript

Below is an example showing how the exact same call can be done in a Unix shell as in a Windows shell. All that is required is that the myscript.R is in the same folder as myscript and myscript.bat. This makes it easier to document and easier to give examples.

Note, for it to work on Unix without having to specify ./myscript when calling it from the same directory, the current diectory has be part of the PATH, e.g. export PATH=".:$PATH". If myscript is placed in a folder that is already in the PATH, the below will work out of the box.

On Linux

$ myscript 1 "2" "3 ab"
myscript.R: Hello world!
[1] "/usr/lib/R/bin/exec/R" "--slave"               "--no-restore"         
[4] "--file=./myscript.R"   "--args"                "1"                    
[7] "2"                     "3 ab"

and also

$ path/to/myscript 1 "2" "3 ab"
myscript.R: Hello world!
[1] "/usr/lib/R/bin/exec/R" "--slave"               "--no-restore"         
[4] "--file=./myscript.R"   "--args"                "1"                    
[7] "2"                     "3 ab"

On Windows

Note how you do not have to specify the *.bat extension when calling a BAT script.

> myscript 1 "2" "3 ab"
myscript.R: Hello world!
[1] "C:\\PROGRA~1\\R\\R-34~1.2\\bin\\x64\\Rterm.exe"
[2] "--slave"
[3] "--no-restore"
[4] "--file=myscript.R"
[5] "--args"
[6] "1"
[7] "2"
[8] "3 ab"

and also

> path\to\myscript 1 "2" "3 ab"
myscript.R: Hello world!
[1] "C:\\PROGRA~1\\R\\R-34~1.2\\bin\\x64\\Rterm.exe"
[2] "--slave"
[3] "--no-restore"
[4] "--file=myscript.R"
[5] "--args"
[6] "1"
[7] "2"
[8] "3 ab"
#! /usr/bin/env bash
# Generic Shell script 'name' that launches 'name.R'
Rscript "$0.R" "$@"
@echo off
@rem # Generic Windows Batch script 'name.bat' for
@rem # launching 'name.R' in the same folder via Rscript
@set bat_path=%~dp0
@set bat_name=%~n0
Rscript "%bat_path%\%bat_name%.R" %*
message("myscript.R: Hello world!")
print(commandArgs())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment