How To Use The Whoami Command on Linux

The Whoami command prints the username with a valid user ID. This command is able to display the name of the logged in user.

Using whoami

Command syntax

whoami [OPTION]

To display the username, enter the following:

whoami

Next, you will see the username (example – user1):

user1

The command can be used in scripts to verify the name of the user who ran the script. Below is an example of using the if statement to compare the name of the user who runs the script with the given string

if [[ "$(whoami)" != "any_name" ]]; then
  echo "Только пользователь 'any_name' может запустить этот скрипт."
  exit 1
fi

If the username does not match the given string, then the script will message echo and exit. Whoami does not accept arguments. If you pass an argument, the command displays an error message:

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

The whoami command accepts only two options:

-h, –help- Show help and exit.

-V, –version- Displays version information.

Alternative Commands

Running the id command with the -un options gives the same result as running whoami:

/usr/bin/id -un

Use the id command for more information about this user. The $ USER environment variable contains the name of the logged in user:

Was this article helpful?

Related Articles