bk6789
bk6789

Reputation: 53

Environment variables when switching users in a bash script

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"

Upvotes: 2

Views: 903

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80931

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.

Upvotes: 2

Related Questions