Something like:
struct uv_passwd
username::Cstring
uid::Clong
gid::Clong
shell::Cstring
homedir::Cstring
end
function username()
for varname in ("LOGNAME", "USER", "LNAME", "USERNAME")
username = get(ENV, varname, "")
!isempty(username) && return username
end
p = Ref{uv_passwd}()
ret = @ccall uv_os_get_passwd(p::Ref{uv_passwd})::Cint
Base.uv_error("get_passwd", ret)
username = unsafe_string(p[].username)
@ccall uv_os_free_passwd(p::Ref{uv_passwd})::Cvoid
return username
end
Note also that you should check whether the environment variables are non-empty, not just whether they exist. This is what Python does.
Update: Alternatively, Julia’s Libc module apparently already contains an undocumented function for this, though it doesn’t check the environment variables first:
julia> Libc.getpwuid(Libc.getuid(), true)
Base.Libc.Passwd("stevenj", 0x00000000000001f5, 0x0000000000000014, "/bin/zsh", "/Users/stevenj", "Steven G. Johnson")
julia> Libc.getpwuid(Libc.getuid(), true).username
"stevenj"
I filed an issue: username() function (analogous to homedir()) · Issue #48302 · JuliaLang/julia · GitHub