Home > database >  what is the bulletproof way to get the user home directory in a script?
what is the bulletproof way to get the user home directory in a script?

Time:06-04

$HOME can be unset. Therefore tilde ~ is the solution. (source: https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html)

Here are my two solutions

HOME="$(cd ~ && pwd)"

and

HOME="$(cd ~ && ${PWD})"

Which should I use? pwd or ${PWD}? Or do you have an other/better solution?

CodePudding user response:

If "bulletproof" means reliably giving the system's idea of the user's home directory, and does not cover the user attempting to stymie this, then for bash you just need to do:

unset HOME
HOME=~

This is because, from reading the bash source code (in particular, the file shell.c), it looks like when HOME is unset, the value of ~ is generally taken directly from the pw_dir field of the entry returned by calling getpwuid on the uid obtained by calling getuid.


It's probably not possible to fully protect against nefarious actions by the caller of your code.

CodePudding user response:

Perhaps something like this would be reasonable bulletproof

HOME=$(/usr/bin/getent passwd $EUID | /usr/bin/cut -d: -f6)

edit 1

As @Shawn mentioned, we can use EUID which is read-only.

edit 2

as @Fravadona noticed, getent is not available on macOS, then either you can write some small C program or even use python (python 2.7 which is still the default on macOS mid-2022)

HOME=$(/usr/bin/python -c 'from __future__ import print_function; import os; import pwd; print(pwd.getpwuid(os.getuid()).pw_dir)')
  • Related