How to switch between users on one terminal?

  • I'd like to log in as a different user without logging out of the current one (on the same terminal). How do I do that?

    I asked a similar question, because I ran into issues with XDG environment variables (`$XDG_RUNTIME_DIR` in particular) that were driving me nuts. -> http://unix.stackexchange.com/questions/354826/how-to-switch-between-users-on-one-terminal-completely-xdg-environment-variab

  • Pratt

    Pratt Correct answer

    10 years ago

    How about using the su command?

    $ whoami
    user1
    $ su - user2
    Password:
    $ whoami
    user2
    $ exit
    logout
    

    If you want to log in as root, there's no need to specify username:

    $ whoami
    user1
    $ su -
    Password:
    $ whoami
    root
    $ exit
    logout
    

    Generally, you can use sudo to launch a new shell as the user you want; the -u flag lets you specify the username you want:

    $ whoami
    user1
    $ sudo -u user2 zsh
    $ whoami
    user2
    

    There are more circuitous ways if you don't have sudo access, like ssh [email protected], but sudo is probably simplest, provided that it's installed and you have permission to use it.

    Also, `su - [user]` may be useful -- the extra dash gives you a login shell.

    I am getting this error "-su: /dev/stderr: Permission denied" after executing this command `echo >>/dev/stderr` on a login with `su --login ...`, any tip? I found this btw http://unix.stackexchange.com/questions/38538/bash-dev-stderr-permission-denied

    Does this allow each new user to have different, overriding values for environment variables? e.g. git config for work, open source, etc.

    One finding, when I listed the `env` it saw that everything was in order as well as a visual inspection can go; And one thing was incorrect: `XAUTHORITY=/home/user1/.Xauthority'. Not sure _why_? So X-window doesn't work by default because the protection on `~/.Xauthority` file is: `-rw-------`. I made a copy and that let me run gedit as an experiment.

    if you get "This account is currently not available": su -s /bin/bash - www-data

    I am slightly off the topic, but mentioning this in case you or someone else can use it. Assuming that you are using a modern OS and have tmux installed (or can install it), one way would be to: 1. Login to the host. 2. Launch a tmux or screen session. 3. Split the pane or open one or more windows as needed. 4. Sudo as the other user as mentioned by others here. 5. Switch back and forth between the users. You need not logout of any session to switch users. Please lookup tmux for shortcuts that can help you save a lot of time.HTH.

    Worth noting: while `sudo -u user …` works fine on Archlnux, however on Ubuntu 18.04. It gives the wrong home directory, e.g. `echo ~` gives root dir for me. Using `su - user` works fine however.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM