Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting $USER inside shell script when running with sudo?

How do I get the correct $USER if I run a shell script with sudo ?

I run them as postinstall scripts in a Mac install package, where they are being sudo-ed automatically, but I need to do stuff with the username.

$HOME is correct, though. The inelegant method would be to extract the name from the home path, but I wonder if there is a natural way to do this.

I can't influence the way the scripts are being called, as it's an automatic call inside the installer.

like image 580
Jörg Haubrichs Avatar asked Oct 27 '09 09:10

Jörg Haubrichs


People also ask

What is $user in shell script?

Syntax. To get the current user name, type: echo "$USER" Get the current user name and store to a shell variable called $u: u="$USER" echo "User name $u"

How do I edit sudoers with Visudo?

As with the /etc/sudoers file itself, you should always edit files within the /etc/sudoers. d directory with visudo . The syntax for editing these files would be: sudo visudo -f /etc/sudoers.

How do I allow user to run sudo?

Adding User to the sudo Group On Ubuntu, the easiest way to grant sudo privileges to a user is by adding the user to the “sudo” group. Members of this group can execute any command as root via sudo and prompted to authenticate themselves with their password when using sudo . We're assuming that the user already exists.


2 Answers

On my system the variable $SUDO_USER is set to the caller's user name.

You shouldn't extract the username from the ${HOME} variable directly. It's being configured and not calculated. To Extract the username you could take a look into /etc/passwd file, but this is very system dependent, e.g. sometimes you have to look into a LDAP directory or the entries are propagated through NIS ...

like image 167
dz. Avatar answered Sep 28 '22 23:09

dz.


You can use $(logname), which returns your login name even if you are currently sudoing.

like image 26
Gauthier Avatar answered Sep 28 '22 21:09

Gauthier