Test a Shell Script with a Temporary HOME Directory
Run a test with HOME=$(mktemp -d) so it cannot touch your real dotfiles. Programs that look the home directory up in the password database ignore the variable.
A test runs a tool that writes to your home directory, and the first failing run overwrites a real configuration file.
tmp=$(mktemp -d)
HOME=$tmp git config --global user.name "Test User"
ls -A "$tmp"
HOME=$tmp python3 -c "import os, pwd; print(os.path.expanduser('~') == '$tmp'); print(pwd.getpwuid(os.getuid()).pw_dir)".gitconfig
True
/rootMost tools take the home directory from the HOME variable, so setting it for one command redirects ~/.gitconfig and its relatives into the temporary directory. The listing shows that Git wrote its file there. The password database is a separate source: pwd.getpwuid still returns the real home, as the last line shows, and any program that asks the system for it directly, rather than reading the variable, ignores your override. The variable is defined in the POSIX environment variables chapter.
Also unset or point XDG_CONFIG_HOME, XDG_CACHE_HOME and XDG_DATA_HOME, because a tool that honors them writes there even when HOME changed. Clean the directory up with trap 'rm -rf "$tmp"' EXIT. For tests that need real isolation, run them in a container or a user namespace instead.