0

When switching from 1 non-root user to another and running the command like following -

beta> exit; sudo su - alpha

Or

beta> exit && sudo su - alpha

But it only logs out and doesn't switch user.

How can this be achieved?

  • 3
    XY problem? What is the real problem you want to solve? Better suggestions that what you think is the solution, may arise. – vanadium Jul 4 at 11:11
  • @vanadium link: XY problem – wjandrea Jul 5 at 0:56
10

exit exits your running shell. But this shell is what would run any subsequent commands. So the next command does not run.

For interactive use, when the shell you start in is an initial login shell, you should probably just log out and back in, in two steps.

For scripting, and for interactive use other than in an initial login shell, the best thing to do would depend on the situation. Wanting to achieve the effect of logging out and back in from a shell that is not an initial login shell (whether in a script or otherwise) is unusual. Even if you managed to do it, it might not be the best approach to whatever underlying problem you are solving.

You can replace your current shell with a new shell running as another user and simulating an initial login shell. When your current shell is an initial login shell, this has mostly the same effect as logging out and back in. It's also not significantly easier than just logging out and back in, which I recommend doing instead.

But if you want to do that, then where the target user is alpha as in your example:

exec su - alpha  # enter alpha's password

By default, with su you only get one try to enter the target user's password. If you enter it incorrectly, you get su: Authentication failure and su quits. But your shell is no longer waiting on the result of the su command; in fact it's no longer running at all. So it's as if you had used exit. But if you enter the password correctly, it works.

If you want to use sudo to do the switch, so you enter your password rather than the target user's password (and you must be a sudoer):

exec sudo -iu alpha  # enter your password

The same issue with your original shell no longer being there to take over if you enter your password wrong still applies. But by default sudo gives you multiple tries to enter your password.

If you really want to use both sudo and su, though there is no need:

exec sudo su - alpha  # enter your password

Putting exec first causes your shell to replace itself with the newly running command, rather than waiting for that command to finish.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.