Get name of current user
Asked Answered
S

1

6

What is a cross-platform way of getting the username of the current user in R? I am currently using

system('whoami', intern=TRUE)

However this assumes that the user has shell access, and that the whoami program is available. Is there a more native to get this information in R?

Swordsman answered 6/7, 2013 at 6:54 Comment(1)
Without R How do people do it in windows usually ? I don't have a windows machineMckee
G
9

I would do this :

 Sys.getenv("USERNAME")  ## works under windows

or better more robust:

 Sys.info()[["user"]]

But under unix-like system the result is sometimes different of system('whoami', intern=TRUE) :

whoami outputs the username that the user is working under, whereas $USER outputs the username that was used to login.

For example, if the user logged in as John and su into root, whoami displays root and echo $USER displays John. This is because the su command does not invoke a login shell by default.

Gazetteer answered 6/7, 2013 at 6:59 Comment(3)
This approach supposed that "USERNAME" variable is already set. I'm using Arch Linux and this is not set by default in my setting but "USER" is set. I think the last approach is more robust or Sys.getenv("USER")Mckee
IIRC, you can use Sys.info()[["effective_user"]] to get the same output as whoami.Dichloride
Perfect! I can't believe I didn't know about Sys.info. I searched the manuals for at least 2 minutes! :)Swordsman

© 2022 - 2024 — McMap. All rights reserved.