Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to create a bash script that must be executed with sudo but should take into account the name of the non-sudo user who executed it. So if user bob runs sudo ./myscript.sh I would like myscript.sh to know bob was the one who executed it.

Let's look inside myscript.sh:

# Do something that takes into account the username.

How can I know the name of the user who spawned the process? More specifically, what should I use instead of whoami to get bob and not root?

share|improve this question
That's not a valid script, I think you meant USER=$(whoami). Note that the USER already exists as a shell internal variable. Also, if it's a bash script, don't run it using sh, which only has a POSIX-compatible subset of features. – nyuszika7h Jun 15 '14 at 11:26
why not edit? fixed now. – marcio Jun 15 '14 at 18:03
It's too trivial, edits need to be at least 6 characters, at least suggested ones. – nyuszika7h Jun 15 '14 at 18:48
ok, I understand. Thanks for the tips :D I usually put a hashbang like this #!/usr/bin/env bash on my bash scripts. – marcio Jun 15 '14 at 21:30
The hashbang is ignored if you call it explicitly with sh or something else. – nyuszika7h Jun 15 '14 at 22:20
up vote 14 down vote accepted

I'm not sure how standard it is, but at least in Ubuntu systems sudo sets the following environment variables (among others - see the ENVIRONMENT section of the sudo manpage):

   SUDO_UID        Set to the user ID of the user who invoked sudo

   SUDO_USER       Set to the login of the user who invoked sudo

for example,

steeldriver@lap-t61p:~$ sudo sh -c 'whoami'
steeldriver@lap-t61p:~$ sudo sh -c 'echo $SUDO_USER'
share|improve this answer
Works as expected on all platforms I tested: debian, fedora(redhat) and freebsd. Thanks! – marcio Jun 15 '14 at 5:03
Confirmed working on a Mac. – SiKing Jun 10 at 17:32

If you want it to work without sudo as well, use ${SUDO_USER:-$USER}. For example:

printf '%s\n' "${SUDO_USER:-$USER}"


${var:-val} will expand to $var, unless it's unset or empty, in which case it will expand to val.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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