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

后端 未结 12 1763
名媛妹妹
名媛妹妹 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:17

    Get the current task's user_struct

    #define get_current_user()              \
    ({                                      \
        struct user_struct *__u;            \
        const struct cred *__cred;          \
        __cred = current_cred();            \
        __u = get_uid(__cred->user);        \
        __u;                                \
    })
    
    0 讨论(0)
  • 2021-01-29 18:22

    Use the standard Unix/Linux/BSD/MacOS command logname to retrieve the logged in user. This ignores the environment as well as sudo, as these are unreliable reporters. It will always print the logged in user's name and then exit. This command has been around since about 1981.

    My-Mac:~ devin$ logname
    devin
    My-Mac:~ devin$ sudo logname
    Password:
    devin
    My-Mac:~ devin$ sudo su -
    My-Mac:~ root# logname
    devin
    My-Mac:~ root# echo $USER
    root
    
    0 讨论(0)
  • 2021-01-29 18:28

    Two commands:

    1. id prints the user id along with the groups. Format: uid=usernumber(username) ...

    2. whoami gives the current user name

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

    On most Linux systems, simply typing whoami on the command line provides the user ID.

    However, on Solaris, you may have to determine the user ID, by determining the UID of the user logged-in through the command below.

    echo $UID
    

    Once the UID is known, find the user by matching the UID against the /etc/passwd file.

    cat /etc/passwd | cut -d":" -f1,3
    
    0 讨论(0)
  • 2021-01-29 18:30

    For Bash, KornShell (ksh), sh, etc. Many of your questions are quickly answered by either:

    man [function]
    

    to get the documentation for the system you are using or usually more conveniently:

    google "man function"

    This may give different results for some things where Linux and Unix have modest differences.

    For this question, just enter "whoami" in your shell.

    To script it:

    myvar=$(whoami)
    
    0 讨论(0)
  • 2021-01-29 18:32

    In Solaris OS I used this command:

    $ who am i     # Remember to use it with space.
    

    On Linux- Someone already answered this in comments.

    $ whoami       # Without space
    
    0 讨论(0)
提交回复
热议问题