I have a bash script and need to execute commands as a different user within the script. But when I switch users, I noticed that the environment variables aren't being reset. For example, if I run the script as user1 and switch to user2, the $HOME environment variable still refers to user1. What's missing?
#!/usr/bin/env bash
whoami # Prints "user1"
sudo -i -u user2 << EOF
whoami # Prints "user2"
echo ${LOGNAME} # Prints "user1", NOT "user2"
echo ${HOME} # Prints "/home/user1", NOT "/home/user2" as expected
EOF
whoami # Prints "user1"