Reputation: 4716
According to this post, I run this from the command line:
USER_HOME=$(getent passwd $SUDO_USER | cut -d: -f6)
and get the following output:
/root
/usr/sbin
/bin
/dev
/bin
/usr/games
/var/cache/man
/var/spool/lpd
/var/mail
/var/spool/news
/var/spool/uucp
/bin
/var/www
/var/backups
/var/list
/var/run/ircd
/var/lib/gnats
/nonexistent
/var/lib/libuuid
/home/user
/var/run/vboxadd
/var/lib/puppet
/var/run/sshd
When I run this in a script (as sudo
, which is the point of the whole thing --- as sudo, ~
expands to /root
):
USER_HOME=$(getent passwd $SUDO_USER | cut -d: -f6)
echo $USER_HOME
I get my correct path /home/user
.
Why can I not invoke my function manually to get the same output?
Upvotes: 0
Views: 78
Reputation: 59072
Because when not using sudo
, $SUDO_USER
is not set and you get the output of getent passwd
without further argument, which lists all users. The cut
then extracts the home directory part.
Replace $SUDO_USER
with $USER
when not running with sudo
.
Note that using getent passwd ${SUDO_USER:-$USER}
should work in both cases.
Upvotes: 5