Programmatically detect RStudio Terminal vs RStudio Console?

To detect whether R is running via RStudio or not, one can check Sys.getenv("RSTUDIO") which is set to 1 when running in RStudio.

How can I detect whether I run R in the RStudio Console or R via the RStudio Terminal? In both cases, RSTUDIO is set to 1. I'm considering inspecting commandArgs()[1], which gives:

> commandArgs()[1]
[1] "RStudio"

in the RStudio Console, and

 commandArgs()[1]
[1] "/usr/lib/R/bin/exec/R"

in the RStudio Terminal.

EDIT: Fixed the commandArgs() example for RStudio Terminal.

That should work! The terminal also sets a couple of environment variables you can use to detect if you're inside one, e.g. you can check to see if the environment variable RSTUDIO_TERM has a value. See here for details:

2 Likes