Home > other >  Exit R terminal by typing `exit`?
Exit R terminal by typing `exit`?

Time:03-09

Almost every tool I use can be exited from terminal by typing exit. But R, being "unique" requires I type q().

Can I set-up something in .Rprofile to achieve this?

CodePudding user response:

Yes, you can add to your .Rprofile:

exit <- list()
class(exit) <- 'exiter'
print.exiter <- function(exiterObject){ q() }

which creates an object exit, assigns it the class exiter, and then overrides the print function to actually call q() by only typing exit (which would normally print the object).

Thanks to this blog for the hack.

CodePudding user response:

R has active bindings for this purpose...

makeActiveBinding("exit", function() q(), .GlobalEnv)

Now getting exit from the global environment triggers a call to q. Hence any of the following would end the R process:

exit
get("exit")
exit   1
typeof(exit)

If necessary, you can remove the binding with rm(exit). You'll find more details, including other ways to interact with bindings, in ?makeActiveBinding.

  • Related