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?

migrated from serverfault.com Apr 9 '17 at 9:22

This question came from our site for system and network administrators.

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
  • AS sven already mentioned. Use single quotes. – Thomas Apr 9 '17 at 9: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 9 '17 at 9: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 9 '17 at 9: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 9 '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 9 '17 at 10:01

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.