Get current username in Julia (Linux)
Asked Answered
M

3

8

I must be doing something stupid, but I can't seem to retrieve the current username using Julia. The closest function in Base appears to be gethostname(), but that returns the computer name, not the username. I tried system calls but am having trouble due to the interpolation character $. Specifically, although echo $USER returns the appropriate username in a terminal, when I try the following in Julia I get various errors or incorrect answers:

run(`echo $USER`)
run(`echo "$USER"`)
run(`echo '$USER'`)
run(`echo '$'USER`)
run(`echo \$USER`)

I guess the issue is that Julia is misinterpreting the $ as an interpolation, but I've got no idea how to get around this.

Any ideas?

Myna answered 7/1, 2015 at 0:53 Comment(1)
FWIW run(`sh -c 'echo $USER'`) would have worked (but the accepted answer is far better!)Lillylillywhite
S
12

An easy workaround:

run(`whoami`)

But unnecessary, as this works:

ENV["USER"]
Stamey answered 7/1, 2015 at 0:59 Comment(2)
Brilliant. The ENV["USER"] approach is definitely the way to go. For the sake of completeness, any chance you could comment on what is going wrong with my echo $USER approach? Either way, +1+Tick (as soon as SO lets me).Myna
run does not run a shell; and the shell is what you need to interpolate the environment variables. run will interpolate Julia variables though, in a shell-like way. Read more here.Stamey
C
3

This works on both Linux and Windows:

splitdir(homedir())[end]
Cyna answered 17/5, 2020 at 18:55 Comment(0)
F
2

A portion of the accepted answer no longer works. Rather than ENV["USER"], the current method is:

ENV["USERNAME"]
Fernandefernandel answered 11/8, 2023 at 16:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.