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.
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"
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.
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.
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 ...
You can use $(logname)
, which returns your login name even if you are currently sudoing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With