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