Score:2

why `su` doesn't change $USER?

bd flag

I've noticed the following:

When I'm using my user, my id is 1000:

┌ sefo@tux ~
└ $ echo $EUID $USER
1000 sefo

When I run su my Id changes but my user doesn't:

┌ sefo@tux ~
└ $ echo $EUID $USER
0 sefo

And, finally, after su - my id and my user change:

┌ root@tux ~
└ $ echo $EUID $USER
0 root

What I'm struggling to understand is why su doesn't change my user. I do believe there is some rationale behind this behavior but at the moment it just seems as inconsistent to me.

Can somebody clarify this behavior?

Saulo avatar
bd flag
bash as root is displayed by my prompt theme (I'm using oh-my-posh to customize the prompt). I presume it reads $EUID to evaluate when to show "as root" or not. I'm going to remove it from the post to prevent further confusion.
Luuk avatar
cn flag
From `man su`: "For backward compatibility, su defaults to not change the current directory and to only set the environment variables HOME and SHELL (**plus USER and LOGNAME if the target user is not root**)"
Saulo avatar
bd flag
I think you nailed it @Luuk. If you turn your comment into an answer I can accept it.
Saulo avatar
bd flag
@steeldriver the commands are those I mentioned in my question: `su` and `su -`. I'm not doing `sudo su`. After both commands (`su` and `su -`) I was asked for the root password.
Saulo avatar
bd flag
@Luuk sorry I didn't get what you mean. Can you clarify?
Luuk avatar
cn flag
@Saulo: When you need an answer, you can add one yourself, nothing wrong with that. Please do not force me into copy/paste the man-page for you.
Saulo avatar
bd flag
@Luuk it wasn't my intention to force you to do anything. I just tried to give you the chance to get the deserved credits for finding what seems to be right answer to my initial question. I'll create the answer. Thank you for the time you spent.
Score:1
bd flag

As correctly pointed out by @luuk, man su states:

For backward compatibility, su defaults to not change the current directory and to only set the environment variables HOME and SHELL (plus USER and LOGNAME if the target user is not root)

Since su targets the root user, for backward compatibility ,$USER (and $LOGNAME) are preserved.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.