How can I get the current user's username in Bash?

后端 未结 12 1788
名媛妹妹
名媛妹妹 2021-01-29 18:04

I am writing a program in Bash that needs to get the user\'s username.

I have heard of a thing called whoami, but I have no idea what it does or how to use it.

W

12条回答
  •  广开言路
    2021-01-29 18:35

    A hack the I've used on Solaris 9 and Linux and which works fine for both of them:

    ps -o user= -p $$ | awk '{print $1}'
    

    This snippet prints the name of the user with the current EUID.

    NOTE: you need Bash as the interpreter here.

    On Solaris you have problems with methods, described above:

    • id does not accept the -u and -n parameters (so you will have to parse the output)
    • whoami does not exist (by default)
    • who am I prints owner of current terminal (ignores EUID)
    • $USER variable is set correctly only after reading profile files (for example, /etc/profile)

提交回复
热议问题