Last active
April 9, 2021 10:09
-
-
Save ormaaj/8f6cd6082e6c2bed237e to your computer and use it in GitHub Desktop.
set HOME and USER
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Try hard to set HOME and USER correctly. | |
# Supply a list of methods and try them until one is successful | |
function forceEnv { | |
typeset -A methods | |
until | |
case ${1+_}${1-unset} in | |
${methods[_$1]+*}) shift; continue ;; | |
unset) echo 'None of the supplied methods were successful.' >&2; return 1 ;; | |
_getent) getent passwd "${EUID:-$(id -u)}" | IFS=: read -r USER HOME{,,,,} SHELL ;; | |
_logname) USER=$(logname) && eval "HOME=~${USER}" ;; | |
_who) who -mT | IFS=' ' read -r USER _ && eval "HOME=~${USER}" ;; | |
*) printf -- 'Invalid method: %q\n' "$1" >&2 | |
esac | |
[[ $? -eq 0 && $USER =~ ^[a-z_][a-z0-9_-]{0,31}[$]?$ && -d $HOME ]] | |
do | |
methods[_$1]= | |
shift | |
done | |
} | |
HOME= USER= | |
forceEnv getent logname who | |
echo "${HOME} ${USER} $?" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment