If I don't fix this I can't properly run bash scripts that checks whether the $USER is root in an IF statement, because, as it is, the $USER is never root, even when the whoami is the root. No matter if I su to root, I keep being whatever user I was before, at least for the $USER variable. How do I fix this? I have tried setting the variable $USER to be equal to the output of the command whoami on the .zshrc file, but it didnt work at all.
Asked
Active
Viewed 633 times
1
-
1Are you running `su` or `su -`. The first does not set `$USER` to the new user as it's not regarded as a new login environment. As ever, check the man page for details - `initializes the environment variables HOME, SHELL, USER, LOGNAME, and PATH` – Bib Aug 25 '22 at 15:56
-
What shell are you using? The tags mentions bash, but the text implies zsh. – Kusalananda Aug 25 '22 at 16:00
-
Since you are having issues with the value of `$USER` when you switch over to root in a way that does not reset this variable, why don't you instead write the script so that it relies on `whoami` or `id` to tell you who the current user is? Also, did you _export_ `USER` somewhere? How are you running that script? What shell is the script written for? – Kusalananda Aug 25 '22 at 16:17
-
Don't trust `$USER`. See `export USER=root` – roaima Aug 25 '22 at 20:50
-
Any reason you can't just use `if [[ "$(whoami)" == "root" ]] ; then` in the script, and ignore `$USER` altogether? – frabjous Aug 25 '22 at 22:22