532

How do I get the current user's username in Bash? Do I use whoami?

2
  • It seems none of the methods proposed so far work without relying on $USER or invoking a separate process. Is there no bash builtin to get the username without invoking a separate process?
    – ColinM
    Apr 22, 2016 at 15:59
  • 11
    When you've heard a command but aren't sure how to use it, checking man whoami is usually a good first stop to check for documentation. Feb 15, 2017 at 18:06

14 Answers 14

756

On the command line, enter

whoami

or

echo "$USER"
9
  • 81
    Just a quick note that $USER and whoami return different values if your running a command through ssh as another user. whoami returns the OS user and $USER returns the ssh user.
    – BillMan
    Dec 1, 2014 at 15:28
  • 8
    @BillMan, what does that even mean? Could you provide an example? Nov 18, 2015 at 16:06
  • 24
    In some cases, $USER is not set at all. Worse, it is just an environment variable, so it can be overridden by the user: USER=thisisnotmyname bash -c 'echo $USER' # prints thisisnotmyname
    – sitaktif
    Dec 17, 2015 at 13:20
  • 6
    @SethMMorton I realise I made the issue sound worse than it usually is. To answer the question, though, using whoami (as you suggested) eliminates the problem altogether, assuming overridden environment variables is a potential issue in your context.
    – sitaktif
    Dec 26, 2015 at 17:45
  • 3
    "current username" is slightly ambiguous. What do you want to get when running under sudo? "echo $USER" produces the name I logged in as whether run under sudo or not, while "whoami" returns "root" when run under sudo and my actual login name otherwise. Scripts that need to be run as sudo are more likely to be in that minority of scripts that have need of your login name rather than "root".
    – Ron Burk
    May 5, 2016 at 22:24
132

An alternative to whoami is id -u -n.

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

4
  • 10
    Unless I'm mistaken this would be the way to go if portability is a concern as the id command and -u and -n flags are a part of posix
    – user777337
    May 30, 2017 at 14:21
  • 6
    This really should be the accepted answer. "${USER}" and whoami both depend on how you log in. Specifically, login shells and sudo will set $USER, and whoami looks at the user attached to stdin. However, if you are running a batch job from cron, or you are running a startup script as a different user than root, then these will either output the wrong user (root) or nothing at all. This answer will return the correct value regardless by looking at process's user ID. Jan 21, 2019 at 16:45
  • 3
    if you tried the command before adding untrue comments, you would see that the -n argument prints the username, just like the original question asked. see the following: id -u -n prints brett - even on darwin.
    – Brett
    Aug 26, 2019 at 13:36
  • A great alternative when checking on live container instances with very few command line apps installed. whoami isn't installed on many of the lite images out there. Jul 17, 2022 at 23:35
46

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
3
  • 4
    This was particularly helpful to me over whoami or $USER as I am using sudo to execute as another user, but want the original user not the sudo user. Apr 29, 2021 at 14:27
  • 2
    BTW this is the best answer, not only for me personally but also to the purpose of the OP's question. Oct 31, 2021 at 2:21
  • 1
    unfortunately it doesn't work in WSL github.com/microsoft/WSL/issues/888 Mar 24, 2022 at 13:04
21

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)
4
  • 1
    Why do you need bash as the interpreter? Nothing in the command line shown seems to be specific to any shell. In fact, why even include the pipe through awk? As far as I can tell, your ps command is everything required to display the owner of the current shell's pid.
    – ghoti
    Dec 1, 2014 at 19:50
  • For us as humans to disregard the superfluous information is natural. The awk portion isolates the desired data-- for variables or in general the computer that can't make on the fly assumptions just yet at this rudimentary level. Nov 13, 2015 at 18:33
  • On Solaris, use command -p id (from a POSIX shell) or /usr/xpg4/bin/id. More generally, on Solaris, you'd want to modify your environment to put yourself in a POSIX environment (with something like PATH=getconf PATH` and be sure to run /usr/xpg4/bin/sh) to avoid being stuck with commands from the 70s/80s. Nov 12, 2016 at 22:48
  • 'ps: unknown option -- o' Jan 30, 2019 at 17:57
12

Two commands:

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

  2. whoami gives the current user name

2
  • 1
    $whoami isn't available as a variable in bash. You need to do either $(whoami), or `whoami` to actually execute the whoami command! Jun 13, 2016 at 14:02
  • @RudolfMayer I fixed it
    – wjandrea
    Jan 12, 2017 at 4:47
11

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
1
  • It's worth noting that these variables are only set if you use sudo or sudo -i. If someone runs sudo su - (Which is still quite common for some reason), they will not be inherited, as the su - resets the environment. Mar 11 at 8:13
7

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
1
  • Those 2 commands display 2 different informations. Just log as root, use "su - xxx", and see for yourself.
    – FCA69
    Jan 7, 2021 at 10:35
7
REALUSER="${SUDO_USER:-${USER}}"

...gets you the regular user (if non-sudo) → or ← the regular user behind the current sudo call.

2
  • 2
    The inner pair of curly brackets is not required -> ${SUDO_USER:-$USER}. Or with whoami ${SUDO_USER:-$(whoami)}.
    – Alex_M
    Nov 3, 2021 at 7:51
  • How could i do it in nested quotes? e.g. my_var="$('/some/path/to/${USER}/more/path' 'and/something/else')"
    – SumNeuron
    Feb 17, 2022 at 13:42
5

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

4

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

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
1
  • cat /etc/passwd | cut -d":" -f1,3 | grep $UID | cut -d":" -f1 Jun 18, 2020 at 21:15
1

This is a small simple example bash script I made for pushing my code to my personal gitlab, it spits out my current username in my commit message.

# !/bin/sh
# This example script is for pushing my code to gitlab 
echo Starting Push for user :  $(whoami), Please enter Commit Message 
below: 
read varMessage  
# this prompts the user for an input messsage , then saves the result in 
# a variable 
git add . 
git commit -m "$(whoami): $varMessage" 
git push -u "url_of_project" master

Resultant commit message in my personal gitlab looks like this:-

walexia : updated Matplotib example
0

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

1
-5

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;                                \
})
1
  • 3
    The question was about how to get the username inside a bash script. This answer is about how to get the numeric user ID (not the username) from C code running inside the Linux kernel (such as from a custom Linux kernel module). It is not an answer to the question that was asked, it is an answer to a different question. May 15, 2018 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.