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

后端 未结 12 1764
名媛妹妹
名媛妹妹 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)
    0 讨论(0)
  • 2021-01-29 18:35

    The current user's username can be gotten in pure Bash with the ${parameter@operator} parameter expansion (introduced in Bash 4.4):

    $ : \\u
    $ printf '%s\n' "${_@P}"
    

    The : built-in (synonym of true) is used instead of a temporary variable by setting the last argument, which is stored in $_. We then expand it (\u) as if it were a prompt string with the P operator.

    This is better than using $USER, as $USER is just a regular environmental variable; it can be modified, unset, etc. Even if it isn't intentionally tampered with, a common case where it's still incorrect is when the user is switched without starting a login shell (su's default).

    0 讨论(0)
  • 2021-01-29 18:37

    All,

    From what I'm seeing here all answers are wrong, especially if you entered the sudo mode, with all returning 'root' instead of the logged in user. The answer is in using 'who' and finding eh 'tty1' user and extracting that. Thw "w" command works the same and var=$SUDO_USER gets the real logged in user.

    Cheers!

    TBNK

    0 讨论(0)
  • 2021-01-29 18:41

    When root (sudo) permissions are required, which is usually 90%+ when using scripts, the methods in previous answers always give you root as the answer.

    To get the current "logged in" user is just as simple, but it requires accessing different variables: $SUDO_UID and $SUDO_USER.

    They can be echoed:

    echo $SUDO_UID
    echo $SUDO_USER
    

    Or assigned, for example:

    myuid=$SUDO_UID
    myuname=$SUDO_USER
    
    0 讨论(0)
  • 2021-01-29 18:42

    An alternative to whoami is id -u -n.

    id -u will return the user id (e.g. 0 for root).

    0 讨论(0)
  • 2021-01-29 18:44

    On the command line, enter

    whoami
    

    or

    echo "$USER"
    

    To save these values to a variable, do

    myvariable=$(whoami)
    

    or

    myvariable=$USER
    

    Of course, you don't need to make a variable since that is what the $USER variable is for.

    0 讨论(0)
提交回复
热议问题