[R] Is it possible to detect whether running as Rscript?

Peter Meilstrup peter.meilstrup at gmail.com
Tue Nov 10 11:54:08 CET 2009


I would like to write a block of code that runs when a script is being  
run from Rscript, but not to run if the same file is being source()d,  
or submitted via ESS, etc. As a gloss I would like to write a file  
that looks somewhat like:

#!/usr/bin/env Rscript

my.func <- function(...) {
	#do something...
}

if ( #is.running.Rscript# ) {
	do.call(my.func, commandArgs(trailingOnly=TRUE))
}

If it helps, I'm thinking of something similar to the Python idiom of  
writing

#!/usr/bin/env python

#class, function definitions

if (__name__=='__main__'):
	#code to be executed when running this file directly

The intent is to use R's debugging facilities to help solve a problem  
that occurs when a script is invoked (from a makefile) with particular  
arguments. So if the makefile invokes "my.script datafile" then I can  
track down the problem by sourcing the script into R and trying  
my.func("datafile")

Is this doable, or is there a better alternative?

Peter




More information about the R-help mailing list