Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Last active April 9, 2021 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ormaaj/8f6cd6082e6c2bed237e to your computer and use it in GitHub Desktop.
Save ormaaj/8f6cd6082e6c2bed237e to your computer and use it in GitHub Desktop.
set HOME and USER
# 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