What does su – `whoami` command do?

I am running a script in my project and I see this command

su - `whoami`

I am having a few basic questions:

  1. What does this command do ?
  2. What is the significance of “ quotes outside the whoami command ?
  3. What is – used for ?

I know su stands for switch user.

Asked By: Sachin Jain


The backticks (``) are command substitution: they are replaced by the result of running the command inside the backticks. Here they run whoami, which prints your username.

The - after su makes su run a login shell: a login shell will read certain environment configuration from scratch, among other things. By default it would just run the user’s shell as an ordinary shell, which won’t do all that work (see the link).

su always starts a new user session, reauthenticating the user as though they’d logged in from scratch. Any environment variables from the outside are cleared out in the inner shell.

So all together this equates to the command (supposing your username on the machine is also “blunderboy“):

su - blunderboy

which means “reauthenticate a new session as blunderboy and run a login shell”.

The overall result of this command is to start a new session as though from scratch, as the current user. Why bother to do that? Likely to pick up on some side effects of su: in particular, because it starts a new user session, it will pick up on any changes to the groups the user is in, as well as other user or permission changes, and and environment variables are all reset. Ordinarily, adding a user to a new group won’t take effect until they log in again┬╣: su counts as logging in again for that purpose, so the shell it starts will have the new group active.

┬╣ This is a simplification, but true enough for this explanation.

Answered By: Michael Homer
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.