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?
Assume we have two users: user1 (an admin) and user2 (a standard user)
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?
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
sudo su - user2 -c "HOME=aaa echo $HOME"
but it still returns $HOME=/home/user1
– thn
Apr 09 '17 at 09:43
... -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
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
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
-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
sudo su
is a useless use ofsu
.sudo
already grants you root access, you don't needsu
to do it again. – phemmer Apr 09 '17 at 13:20