0

Assume we have two users: user1 (an admin) and user2 (a standard user)

  • Login as user1
  • Run

    sudo su - user2 -c "env"
    
  • The result shows $HOME=/home/user2

  • Run

    sudo su - user2 -c "echo $HOME" 
    
  • The result shows $HOME=/home/user1

Why is that?

thn
  • 3

1 Answers1

4

This is because in the second example, the variable $HOME gets expanded before the shell executes the command, so what you are really running is

sudo su - user2 -c "echo /home/user1" 

as that is the value the variable $HOME has at this point.

(I also guess the output of the second command is not really $HOME=/home/user1 but instead just /home/user1).

You could prevent variable expansion in the first shell if you use single quotes:

$ sudo su - user2 -c 'echo $HOME' 
/home/user2
chicks
  • 1,112
Sven
  • 2,427
  • AS sven already mentioned. Use single quotes. – Thomas Apr 09 '17 at 09:30
  • Thanks Sven. I do need variable expansion. If I want to change $HOME when run a command as user2 what can I do?
    I've tried sudo su - user2 -c "HOME=aaa echo $HOME" but it still returns $HOME=/home/user1
    – thn Apr 09 '17 at 09:43
  • That is the same problem. Now you are running ... -c "HOME=aaa echo /home/user1" ... Another option to prevent the expansion would be to escape the $ like so: ... -c "echo \$HOME". This would tell the shell that you want to ignore the special meaning of the $ character and send it down to the su command to execute. – Sven Apr 09 '17 at 09:51
  • This doesn't make any sense. You don't want user1's home to be expanded and with the escape, this doesn't happen. Instead, the command echo $HOME is send to the shell that runs in user2s context and there the variable is expanded to /home/user2. If that still doesn't solve your problem, please ask a new question explaining the whole context of your task because I've answered this question ("Why does this happen"). – Sven Apr 09 '17 at 10:00
  • To be clear: sudo su - user2 -c "echo \$HOME" will result in "/home/user2". The expansion is prevent in the context of user1 and the sudo command, but not in the context of user2. – Sven Apr 09 '17 at 10:01
  • Thanks Sven, I do need expansion as stated because inside -c is actually a complex script. Reading your answer carefully -c "echo \$HOME" actually works for me! Thanks – thn Apr 09 '17 at 10:03