'Behavior of variables using su in linux [duplicate]

I'm installing Poetry in a dockerfile, but I want to do it under a different user (to play nicely with VSCode). I don't understand the behavior of the su command though.

When I run su vscode -c "echo $HOME" I get /root. However, when I run su vscode, and subsequently run echo $HOME, I get /home/vscode`.

Even stranger, when I run su vscode -c "echo $HOME && curl -sSL https://install.python-poetry.org | python3", I get /root as output of the first command, but poetry is installed to /home/vscode/.local/bin. I'm at a loss here... can someone shine some light on this?



Solution 1:[1]

"echo $HOME" is evaluated by your current shell before su is executed. So su will only be passed as argument "echo /root" (already-evaluated). If you want the variable to be evaluated by the shell spawned by su, you need to escape it: 'echo $HOME'

See 2.2 Quoting in the POSIX specification

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1