2

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"

1 Answer 1

2

The variables are being expanded by your current shell. Not by the sudo shell. The sudo shell doesn't see variables it sees literal text.

You need to prevent that. Either by quoting some or all of the heredoc start marker or by escaping the $ in the heredoc contents.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.