Skip to content

Instantly share code, notes, and snippets.

@the-moog
Created June 1, 2023 18:58
Show Gist options
  • Save the-moog/1472aedf0986ded356b1a47a9dd2840f to your computer and use it in GitHub Desktop.
Save the-moog/1472aedf0986ded356b1a47a9dd2840f to your computer and use it in GitHub Desktop.
Bash script to find the true UID and HOME of a user once they have used sudo or are not in an interractive login.
#!/bin/bash
# Bash script, related to https://stackoverflow.com/a/76384868/1364242
# get_real_login.sh
# Get the name at the time of login of the user who is running this script
# MIT License
LICENSE="
Copyright (c) <2023> <https://github.com/the-moog>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"
VERBOSE=0
# Do it lots = use a function
function val () {
echo "$(cat < /dev/stdin)"|tr -d ' \t'|cut -f2 -d:
}
# $$ is the the PID of this script
CPID=$$
# Current user (obviously root)
REAL_UID=$(id -u)
# Fallback HOME
REAL_HOME=/
while [ "${CPID}" -ne 1 ]; do {
# Sadly no do-while
if [ "${CPID}" -ne 1 ]; then
STAT=$(cat /proc/${CPID}/status)
CPID_P=$(echo "${STAT}"|grep PPid|val)
CPN=$(echo "${STAT}"|grep Name|val)
CPUID=$(echo "${STAT}"|grep Uid)
CPUID=$(($(echo ${CPUID}|tr -s ' \t' '::'|val)))
CPUN=$(id -un ${CPUID})
ENV_HOME=$(cat /proc/${CPID}/environ|tr '\0' '\n'|grep HOME|cut -d= -f2)
# Debug output - set VERBOSE=1
test -n "${VERBOSE}" && {
echo "CMD:${CPN}";
echo "PID:${CPID}";
echo "PPID:${CPID_P}";
echo "UID:${CPUID}";
echo "USER:${CPUN}";
} | printf "%-20.20s %-10.10s %-10.10s %-10.10s %-15.15s\n" $(cat < /dev/stdin)
if [ ${CPUID} -ne 0 ]; then
REAL_UID=${CPUID}
fi
test -n "${ENV_HOME}" && REAL_HOME="${ENV_HOME}"
CPID="${CPID_P}"
fi
}; done
REAL_USERNAME=$(id -un ${REAL_UID})
EXISTS=$(test -d $(readlink ${REAL_HOME}) && echo " - EXISTS" || echo " - MISSING !!")
echo -e "\nLogin User: ${REAL_USERNAME} (UID:${REAL_UID}) \${HOME}=\"${REAL_HOME}\"${EXISTS}\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment