2

I'm writing a script to setup new debian install's. The problem is in this code:

if [ ! -z "$USER1" ]
then
    sudo -u "$USER1" bash <<-EOF
    cp "$BASHRC $HOME"/.bashrc
    wget https://raw.github.com/trapd00r/LS_COLORS/master/LS_COLORS -O "$HOME"/.dircolors
    echo 'eval $(dircolors -b $HOME/.dircolors)' >> "$HOME"/.bashrc
    . "$HOME"/.bashrc
    echo "Here is LS_COLORS in action: "
    ls -l "$HOME"/ 
EOF

PROBLEM:

When I sudo to another user the $HOME variable is not showing/changing this new users home directory.

QUESTIONS:

Can you explain to me the problem?

How would I do this in the best and efficient way?

Edit:

Why do I keep getting "cp: cannot stat '': No such file or directory" or "cp: missing opereand" in my cp command? I think it has something to do with $HOME again..........

5

The here-doc content is evaluated BEFORE the sudo is called. This means that every instance of $HOME is in the context of the caller, not the sudo. You can see this in action here:

A=apple
bash <<-EOF
A=banana
echo "$A"
EOF

The output is

apple

If you quote your EOF marker its contents will be quoted correspondingly:

A=apple
bash <<-'EOF'
A=banana
echo "$A"
EOF

Output

banana

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.