How to get a users home directory while running a bash script as root

Here's how to get a user's home directory while running the script as sudo/root in bash.

How to get a users home directory while running a bash script as root
Photo by Gabriel Heinzer / Unsplash

TL;DR

the TL;DR answer for you poor devs that found this on google is:

USER_HOME=$(getent passwd $SUDO_USER | cut -d: -f6)
There is a reason we don't do this with eval commands. See the longer answer below as to why

Longer more complex answer

So there is another more readable way to do this. The first thing that came to mind for me was

USER_HOME=$(eval echo ~${SUDO_USER})
echo ${USER_HOME}

But the problem with this is that it relies on the eval command. The eval command is extremely powerful and easy to abuse. It causes your code to be parsed twice instead of once. This is dangerous because bash will evaluate the contents of that variable. If the variable contains a shell command, the shell might run that command whether you want it to or not. This can lead to unexpected results. Especially when variables can be read from untrusted sources (like users or user-created files)