When switching from 1 non-root user to another and running the command like following -
beta> exit; sudo su - alpha
beta> exit && sudo su - alpha
But it only logs out and doesn't switch user.
How can this be achieved?
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.Sign up to join this community
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
su, though there is no need:
exec sudo su - alpha # enter your password
exec first causes your shell to replace itself with the newly running command, rather than waiting for that command to finish.