Search code examples
rgoogle-colaboratory

How to access the shell in google Colab when running the R kernel


When I use Python with colab, you can access the underlying operating system using things like ! and %%shell, e.g., !ls to list the files.

When I use colab with the R kernel, the ! and %%shell tricks don't work. Is there a way to call the shell from colab in this case?

https://colab.research.google.com/#create=true&language=r


Solution

  • There is the base R function system which allows you to call the shell behind the Notebook. Since colab suppresses the stdout, one needs to set the option intern = TRUE to see the result as an R character vector. To properly display line breaks, I defined a function called shell_call which is analog to ! in ipython:

    shell_call <- function(command, ...) {
      result <- system(command, intern = TRUE, ...)
      cat(paste0(result, collapse = "\n"))
    }
    
    shell_call("ls -lah / | head")
    

    enter image description here