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?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
thn
  • 3
  • 1
  • 1
    Related: http://unix.stackexchange.com/questions/218169/is-there-ever-a-good-reason-to-run-sudo-su – Kusalananda Apr 09 '17 at 09:48
  • `sudo su` is a useless use of `su`. `sudo` already grants you root access, you don't need `su` to do it again. – phemmer Apr 09 '17 at 13:20

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
  • 1
  • 9
  • 27
Sven
  • 2,417
  • 19
  • 15
  • 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 `user2`s 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