This article has been updated to reflect the RStudio terminal feature as of version 2022.07.1+554 of the RStudio IDE.
- General Usage
- Advanced Topics
- Reference
Introduction
The RStudio terminal provides access to the system shell from within the RStudio IDE. It supports full-screen terminal applications such as vim, Emacs, and tmux as, well as regular command-line operations with line-editing and shell history.
Potential uses of the shell including advanced source control operations, execution of long-running jobs, remote logins, system administration of RStudio Workbench or RStudio Server, and the aforementioned full-screen terminal programs.
This article does not attempt to cover fundamentals on when and how to use a system shell. Instead, it focuses on the features, design, options, and limitations of the RStudio terminal feature itself.
Unlike most RStudio features, the nature of the terminal leads to several platform-specific differences. These primarily break down into two categories: Windows, and everything else (Mac, Linux, and Server). Appendix A provides a summary.
Getting Started
The Terminal tab is next to the Console tab. Click on the Terminal tab and a new terminal session will be created (if there isn't one already).
- If the tab isn't visible, show it via Shift+Alt+T (Tools->Terminal->Move Focus to Terminal).
- The full list of terminal-related RStudio commands and keyboard shortcuts is in Appendix B. Most terminal-related commands can be found on the Terminal dropdown menu in the terminal pane, and on the Tools->Terminal menu.
Here's a terminal with the output of simple command:
The visual appearance of the terminal is controlled via the Tools->Global Options->Appearance settings.
Multiple Terminals
RStudio supports multiple terminal sessions. To start another terminal session, use the New Terminal command on the Terminal dropdown menu, or Alt+Shift+R.
Each terminal session is independent, with its own system shell process and buffer. Switch between them by (1) using the arrows next to the drop-down menu, (2) clicking on the terminal's name in the drop-down, or (3) using the Previous Terminal/Next Terminal drop-down menu commands. The dropdown button shows the name of the currently selected terminal session ("Terminal 3" in the following screenshot):
Terminal Names
Terminal sessions have a default name, "Terminal 1", "Terminal 2", and so on. Rename the current terminal via the Rename Terminal command on the drop-down. For example, renaming "Terminal 3" to "Remote Session" in the previous example gives this:
Thus, in your workflow, you can create multiple terminals and give them meaningful names to simplify navigation. A collection of named terminals, or "terminal set", is generally associated with an RStudio project. For more details, see Terminal Architecture and Lifetime.
An alternative (or complementary) approach is to use a terminal multiplexer as described in Advanced - Using Tmux or Screen.
Execute in Terminal
When editing files in the RStudio editor, any selection (or the current line if nothing is selected) can be sent to the active terminal via Ctrl+Alt+Enter (also Cmd+Alt+Enter on the Mac). If a single-line was sent to the terminal the cursor will advance automatically to the next line, allowing single-stepping.
In following example, a simple Python source file was loaded, a Python interpreter started in the current terminal, and Ctrl+Alt+Enter used to step through the script:
This is just an example; for more powerful integrated Python support look at the reticulate package.
If a shell file is being edited (*.sh), Ctrl+Enter (plus Cmd+Enter on Mac) can be used to single-step, as can the Run toolbar button. This will also work on Windows, but no check is done that the shell-type loaded in the active terminal session matches the commands being sent.
Note that the Run Script button does the same as prior versions of RStudio, and will save and run the entire script via system() in the R Console. This button does not appear in Windows.
Busy Terminals
Programs running in a terminal do not block the rest of the RStudio user-interface, so work can continue working in RStudio even when one or more terminal sessions have a child process running.
A terminal with child processes is considered busy by RStudio, and will have (busy) next to its name, and the close [x] changes to a stop button.
This "busy detection" feature is only available on Mac, Linux, and RStudio Workbench / RStudio Server and not on Windows. See Appendix A - Platform Specifics for more details.
Closing Terminal Sessions
To close a terminal session, use the Close Terminal command on the Terminal dropdown menu, click the [x] on the far-right of the Terminal pane toolbar, or type exit from within the shell itself.
As discussed earlier, if a terminal is currently busy, the [x] changes to a stop button.
Clicking the stop button will trigger the Interrupt Current Terminal command, sending an interrupt to the terminal; this may close the currently running program (the program itself decides what to do when receiving an interrupt), but will not close the terminal.
Finally, if the terminal feature it not useful to your workflow, you can remove the tab altogether by clicking the [x] on the Terminal tab itself. This will close all running terminal sessions, including any custom-named terminal sessions. Subsequent instances of RStudio will not show the Terminal tab: to bring it back, use Shift+Alt+T (Tools->Terminal->Move Focus to Terminal).
Terminal Buffer
The terminal buffer keeps the last 1000 lines of output when running non-full-screen terminal programs. You can scroll through this buffer using the scrollbars (via the mouse) or a mouse-wheel if your system supports it. Full-screen programs typically have their own built-in buffers and navigation conventions.
Clearing the display with the native shell command (e.g. clear for a Posix-style shell, cls for a Windows Command Prompt, or Clear-Host for PowerShell) will only clear the visible portion of the buffer. To clear the entire buffer, use Ctrl+L when focus is in the terminal.
The mouse can be used to select text in the terminal so it can be copied & pasted elsewhere.
To send the entire terminal buffer to a new RStudio editor buffer, use the Copy Terminal to Editor command on the terminal drop-down menu.
Advanced - Terminal Architecture and Lifetime
Process Model
When a terminal session is started, it launches a shell process (e.g. bash).
The default terminal is started with this command:
/usr/bin/env bash -l
This shell process runs as a child process of the R session process (rsession / rsession.exe) of the current RStudio instance, and will inherit environment variables from that process.
This has an important implication: if the R session is suspended, closed, and/or restarted, the terminal shells, and their child processes, will be killed. This is why RStudio warns before this happens as described above in Busy Terminals.
In an RStudio Workbench or RStudio Server environment, the terminal shells are therefore running under the same user account, and with the same privileges, as the R session, all of which takes place on the server and not on the device where the web browser is running. The security of those terminal shells is wrapped within the same security model as the R session.
On a desktop RStudio IDE, the terminal shells are running locally, with the same rights as user who launched RStudio, but they are running as children of the rsession process, the same as on an RStudio Workbench or RStudio Server environment. This may be changed in a future release to optimize the performance and behavior of the terminal feature on desktop IDEs.
Terminal Persistence
RStudio mitigates the terminal's lifetime being tied to that of the R session by saving and restoring several aspects of the terminal session:
- The list of open terminal sessions, and their Terminal Names.
- Terminal Buffers (with limits as described)
- Environment Variables (Mac / Linux / Server only, and does not include shell variables)
- Current Working Directory (Mac / Linux / Server only)
Terminal Restoration
When RStudio starts up, it loads the previously persisted metadata, initially repopulating the dropdown list of known terminals. Terminal shells are not restarted until the user makes a particular terminal session visible. At that point the shell is restarted, and the buffer and environment restored (where supported).
This mechanism will not restore previously running processes other than the terminal shell. If a long-running operation was killed (including full-screen programs) by an action that required stopping the R session, then work within that process could have been lost.
Note: Terminals configured to use Windows Command-Prompt or PowerShell will not have their buffers restored; they will always restart with a clean buffer.
Command history within the shell is handled by the shell; RStudio does not do anything to persist or restore shell command history.
Advanced - Use RTOOLS4 Bash on Windows
The RTools40 toolchain bundle for Windows includes its own set of Posix-based tools, including a bash shell. Some users may want to use this as their shell instead of git-bash. This can be done by configuring a custom terminal as follows:
More on RTools40 for Windows: https://cran.r-project.org/bin/windows/Rtools/
Advanced - Environment Variables
The terminal shell is started as a child process of the current rsession and will inherit its environment variables. Additionally, within a terminal session, the following environment variable is set on all platforms.
- RSTUDIO=1
The following are only set on Mac, Linux, and Server (shown with example values):
- RSTUDIO_TERM=C36329F1 (unique id for current terminal)
- RSTUDIO_PROJ_NAME=mypackage (base name of current project)
- RSTUDIO_SESSION_ID=E2F866DC (unique id of current r session)
This can be helpful in doing advanced shell customization.
Advanced - Using Tmux or Screen (Mac/Linux/Server)
Terminal multiplexers such as tmux or screen can facilitate keeping terminal sessions alive even when the R session is restarted (in addition to the other benefits of their use).
RStudio does not directly support these, so it is up to you or your administrator to install and configure (and learn to use) a terminal multiplexer. This section is to give ideas on how you might make use of them with RStudio.
Here is a basic example of configuring tmux to automatically creates a project-specific session in the terminal. You would have to adjust it for your system and desired goals. For example, if you are on a multi-session Server environment, you might want to include the $RSTUDIO_SESSION_ID in the name of the tmux session. Similarly, if you want to combine using tmux and multiple RStudio terminal sessions within an RStudio project, you could also scope the tmux sessions via $RSTUDIO_TERM.
Go to Tools->Global Options->Terminal. Specify a Custom terminal, give the full path to the shell, and have it load a custom startup file (.rstudio-bashrc, contents shown below the screenshot; the name of the file has no special significance).
Under Process Termination, tell the shell not to warn about processes on a whitelist. This lets you restart R without being warned if a shell is running that process. Since tmux will keep the session alive, and RStudio will reconnect when you revisit the terminal tab, the warning is not needed.
The .rstudio-bashrc file contains the following commands, which will try to attach to a tmux session based on the name of the current project, and create one if it does not exist. It also loads the (Mac-specific) default bash profile. Obviously, adjust to your environment as needed.
source /private/etc/bashrc
tmux attach -t rstudio-$RSTUDIO_PROJ_NAME 2> /dev/null || tmux new -s rstudio-$RSTUDIO_PROJ_NAME
Again, RStudio does not have any special handling of tmux, screen, or any other terminal multiplexer. The example given above, on a multi-user server, could quickly lead to a large number of running tmux sessions. Management of these has to happen independent of RStudio.
Terminal multiplexers such as tmux or screen can facilitate keeping terminal sessions alive even when the R session is restarted (in addition to the other benefits of their use).
Advanced - Workbench Support for Multiple R Versions
RStudio Workbench provides the ability to switch between different versions of R, but the terminal feature is not aware of this mechanism and will always launch the default version of R.
Here's a screenshot showing Workbench set to use R 3.6.3, but the terminal is using 4.1.3. You may also see "WARNING: ignoring environment value of R_HOME" when starting R in the terminal in this scenario.
To work around this limitation, add the following to the end of ~/.bashrc (or the appropriate shell configuration file for your system):
if [[ -v RSTUDIO && -v R_HOME ]]; then
export PATH="${R_HOME}/bin:$PATH"
fi
This will detect that the terminal is running inside the RStudio IDE, and that R_HOME is set, and put that version of R first on the path.
Appendix A - Platform Specifics
Here is a summary of the major platform differences, as of RStudio 2022.07.1+554.
Windows Desktop IDE
[+] shows a Windows-IDE specific feature
[x] shows a feature not supported by Windows IDE
- [+] Choose between Git-Bash, Command Prompt, PowerShell, PowerShell Core, and Windows Subsystem for Linux (WSL), if available
- [x] "Busy-detection" and a Stop Sign button
- [x] Capture and restore environment variables
- [x] Reloading of terminal buffer for Command Prompt or PowerShell terminals
- [x] Local terminal echo
Appendix B - Options (All Platforms)
Note that many terminal options require starting a new terminal session before it takes effect.
Tools->Global Options->Terminal
- Initial directory: Project directory, Current Directory, or Home directory
- New terminals open with Custom: specify full path and options for the terminal shell
- Connect with WebSockets: terminals will try to use WebSockets to talk to the shell process
- Hardware acceleration: use hardware for terminal rendering via HTML canvas
- Audible bell
- When shell exits: Automatically closed Terminal pane when the shell exits?
Tools->Global Options->Appearance
- Visual appearance of the terminal emulator
Tools-Global Options->Code->Display
- Blinking cursor: does the terminal cursor blink?
Appendix C - Options (Mac/Linux/Server-Only)
Tools->Global Options->Terminal
- New terminals open with Bash (default): shells use "/usr/bin/env bash -l"
- New terminals open with Zsh: if found in /etc/shells
- Local terminal echo: immediately echo keyboard input to the terminal, then reconcile with echo from the server; auto-disabled when running a full-screen program
- Save and restore environment variables: runs a hidden command to capture and preserve terminal environment variables; may need to be disabled with some custom shell configurations, and relies on HISTCONTROL=ignoredspace (or ignoreboth) to prevent hidden commands from showing up in shell history; the symptom of this misbehaving are commands of the form "echo ######## && /usr/bin/env && echo ########", where ######## is some random sequence of characters, showing up in the shell history, such as when user hits the up-arrow to go to previous command
- Ask before killing processes Always (default): if the shell has any child processes, RStudio will warn before killing the shell
- Ask before killing processes Never: RStudio never warns before killing a shell, even if it has child processes
- Ask before killing processes Always except for whitelist: Same as "Always" except if one of the processes listed (default is tmux or screen) is running, then same as "Never".
Appendix D - Options (Windows-Only)
Tools->Global Options-Terminal
- New Terminals open with Git Bash: Use the git-bash shell found with Git for Windows, if installed
- New Terminals open with Command Prompt: Use the standard Windows command prompt
- New Terminals open with PowerShell: Use the Windows PowerShell, if available
- New Terminals open with PowerShell Core: Use PowerShell Core, if available
- New Terminals open with Bash (Windows Subsystem for Linux): requires 64-bit Windows-10, and must be separately installed
[End of document]
Comments