Ask Ubuntu is a question and answer site for Ubuntu users and developers. 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

A weird question, I know. Here's the script:

echo $USER

Here's the command I use to run it:

sudo ./myscript.sh

Right now it prints "root" but I want it to print jon, my username. Is there a way to do that by changing the script, and not the command?

share|improve this question
    
Yes, there are ways to do it. But maybe the easiest way is a work-around. Call that script from another script, where you 'save' your user id so that the 'sudo script' can access it. – sudodus 4 hours ago
up vote 11 down vote accepted

Use the SUDO_USER environment variable instead of USER.

sudo places the name of the user who ran it in the SUDO_USER environment variable:

ek@Io:~$ sudo sh -c 'echo $USER'
[sudo] password for ek:
root
ek@Io:~$ sudo sh -c 'echo $SUDO_USER'
ek

So you can simply replace $USER with $SUDO_USER in your script:

echo $SUDO_USER

Further Reading

share|improve this answer

Your Answer

 
discard

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.