Getting $USER inside shell script when running with sudo?
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.
Inspect the variable SUDO_USER.
http://www.gratisoft.us/sudo/man/sudo.html#environment
Another way to get the user is via the who command. This is useful sometimes when you don't care if the user has sudo'd or not.
who -m | awk '{print $1;}'