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

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

提交回复
热议问题