13

I feel like this should be straightforward but I've never seen anyone ask this that I can tell. The situation is pretty straight forward. Whenever I become a user, ie su user it always starts in /root directory instead of it's home directory. Let me show you.

[root@st-test2 ~]# grep "postgres" /etc/passwd
postgres:x:26:26:PostgreSQL Server:/var/lib/pgsql/:/bin/bash
[root@st-test2 ~]# su postgres
bash-4.2$ pwd
/root
[root@st-test2 ~]# ls -lhart /var/lib |grep postgres
drwx------.  4 postgres postgres   86 May  5 16:07 pgsql

So, you can see that the postgres user's home directory exists and that its set in /etc/passwd...but for some reason, they start in the root directory. This happens with every user that I have created and I have no idea why. I can't say that I've ever seen this happen before either.

Chris Jones
  • 233
  • 2
  • 5

2 Answers2

35

If you only give a username as argument, su changes user without changing much else:

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).

So su postgres stays in the same directory. However since HOME is set to the new user’s home directory, cd will take you to the right place.

To log in and start from the user’s default directory, you need to ask su to start a login shell set up appropriately:

su -l postgres

or its common synonym,

su - postgres
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
  • 2
    I guess that is it. My employer has it setup where su - also goes to user's home directory and I thought that my test servers not doing that was causing an issue, but now I am thinking that my employer has an alias somewhere and also that su - not going to the home directory didn't cause an issue. Thanks for the explanation! I really should just read the man file more often. – Chris Jones May 06 '21 at 12:47
  • This is why it's a good idea to name aliases differently. – reinierpost May 06 '21 at 22:28
1

Your employer may have changed this because Debian changed the su behavior since Buster. NewInBuster I also created the alias su='su -'

boldsuck
  • 11
  • 3