How to use Whoami Command

How To Use Whoami Command

In this article, we will cover the whoami command.

As its name suggests, the whoami command prints the user name of the effective user ID. In other words, it displays the name of the currently logged-in user.

 

How to Use the whoami Command

The syntax for the whoami command is as follows:

whoami [OPTION]

 

To display the name of the currently logged user, invoke the command without any options:

whoami

Output similar to the following will be displayed on the screen, showing the name of the user invoking the command:

root

You can use the whoami command in shell scripts to check the user’s name running the script.

Here is an example using an if statement to compare the user’s name running the script with a given string.

if [[ "$(whoami)" != "any_name" ]]; then
  echo "Only user 'any_name' can run this script."
  exit 1
fi

 

If the user name does not match the given string, the script will echo a message and exit.

The whoami command is also handy for verifying the user’s name after switching to another user with the su command.

whoami does not accept arguments. If you pass an argument, the command prints an error message:

whoami: extra operand ‘anything’
Try 'whoami --help' for more information.

The whoami command accepts only two options:

  • -h, –help – Display a help message and exit.

  • -V, –version – Shows the version information and exit.

 

Alternative Commands

Running the id command with the -un options produces the same output as running whoami:

whoami [OPTION]

 

Use the id command to obtain more information about a given user.

The $USER environment variable contains the name of the logged-in user:

echo $USER

 

Conclusion

The whoami command is a compound of the words “Who am I?” and prints the name of the user associated with the current effective user ID.