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

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

    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).

提交回复
热议问题