Tuesday, May 7, 2024
24
rated 0 times [  24] [ 0]  / answers: 1 / hits: 13633  / 1 Year ago, tue, february 14, 2023, 11:44:56

I expected the -H option to give me the target user's environment.




nbest@geo:~$ sudo -H -u tanum echo $HOME
/home/nbest
nbest@geo:~$ sudo -u tanum echo $HOME
/home/nbest
nbest@geo:~$ sudo -i -u tanum echo $HOME
/home/nbest
nbest@geo:~$ sudo -H -i -u tanum echo $HOME
/home/nbest


This would allow me to say:



sudo -u tanum ls ~


and get the target user's home directory listing. Not the case. Is this caused by the env_reset default in sudoers?



If so does -H have any effect? What is the safest way to override this behavior?



If not what is the intended effect of -H?



Please set me straight.


More From » command-line

 Answers
7

$HOME and ~ get expanded by your shell, they are not interpreted by echo.



In other words, echo does not see $HOME as an argument. It actually sees /home/nbest. Therefore the following commands are exactly identical (in your case):



nbest@geo:~$ sudo -H -u tanum echo $HOME
nbest@geo:~$ sudo -H -u tanum echo /home/nbest


Whatever you try (-H, -i, ...) you will never obtain the wanted behavior. Because $HOME is replaced by your shell and your shell runs as your user. sudo does not affect your shell in any way.






To work around this 'issue' (which actually is a feature), you can start a new subshell:



nbest@geo:~$ sudo -H -u tanum sh -c 'echo $HOME'


(Note that I'm using single quotes to avoid expansion.) This way, the new shell sh will run as user tanum and print his home directory.






An another alternative is to use ~username, which gets expanded to the home of that user, without the need of using sudo or su. Try:



nbest@geo:~$ echo ~tanum

[#29724] Wednesday, February 15, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
guialk

Total Points: 300
Total Questions: 144
Total Answers: 121

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
;