Full file path of current RStudio script

Get full path to current R script

Are you wondering where is my current R script file located and how to determine the full path?
Here is how to do that in RStudio or while running in batch mode.

Path to saved R script in RStudio

If the saved script is already open, you can use this code in the console. As a result, you will get the full file path.

  sep = '/'

You can execute the function getSourceEditorContext() by itself to get more information about your current script.

Location of the unsaved RStudio script in Windows

If you have an unsaved RStudio script and RStudio is open, then try to look at this directory.


There should be a folder that starts with “s-” and contains what you are looking for. It might be helpful to know when you accidentally closed an unsaved script.

If there is not, then try to look at the same thing in another RStudio-related folder.



Get current R script location in batch mode

If you are running your R script in non-interactive mode (batch mode), then you can use the function commandArgs to get the R script location. For example, if I’m running an R script from the Windows command line here is the result.

My script contains this code.

print(commandArgs(trailingOnly = FALSE))

This is the result that I will get while running the script from the command line.

[1] "C:\\PROGRA~1\\R\\R-36~1.1\\bin\\x64\\Rterm.exe"
[2] "--slave"
[3] "--no-restore"
[4] "--file=C:\\MyLocation\\locate.R"

By knowing the location of the path to the current R script that is executed in batch mode, you can extract that like this. Function dirname is returning only the directory of the file.

  "--file=", "", commandArgs(trailingOnly = FALSE)[4]

After saving and running this script from the command line you will get where it is located.

[1] "C:/MyLocation"

To get the full path to the current R script in batch mode use this code.

print(sub("--file=", "", commandArgs(trailingOnly = FALSE)[4]))


Get the path to the current R script depending on the running mode

If you are using RStudio to run the R script in interactive mode and sometimes in non-interactive mode, you can detect that and return the necessary path.

nimode <- sub("--file=", "", commandArgs(trailingOnly = FALSE)[4])

  commandArgs(trailingOnly = FALSE)[2] == "--interactive",
    sep = '/'

#[1] "C:/MyLocation/locate.R"



I hope it helps, and please check out other posts about quick R tips.