When I'm doing something that requires root be typed in dozens of times in a row, I prefer to switch my session to a root session. In the various tutorials and instructions I have used on the Internet, I see sudo su
, sudo su -
, sudo -i
and sudo /bin/bash
being used to open a root session, but I'm not clear on the difference between these and when or if that difference matters.
Can someone clear this up for me?
To explain this you need to know what the programs do:
su
- The commandsu
is used to switch to another user (s witch u ser), but you can also switch to the root user by invoking the command with no parameter.su
asks you for the password of the user to switch, after typing the password you switched to the user's environment.sudo
-sudo
is meant to run a single command with root privileges. But unlikesu
it prompts you for the password of the current user. This user must be in the sudoers file (or a group that is in the sudoers file). By default, Ubuntu "remembers" your password for 15 minutes, so that you don't have to type your password every time.bash
- A text-interface to interact with the computer. It's important to understand the difference between login, non-login, interactive and non-interactive shells:Types of shells:
So the cases are:
sudo su
Callssudo
with the commandsu
. Bash is called as interactive non-login shell. So bash only executes.bashrc
. You can see that after switching to root you are still in the same directory:sudo su -
This time it is a login shell, so/etc/profile
,.profile
and.bashrc
are executed and you will find yourself in root's home directory with root's environment.sudo -i
It is nearly the same assudo su -
The -i (simulate initial login) option runs the shell specified by the password database entry of the target user as a login shell. This means that login-specific resource files such as.profile
,.bashrc
or.login
will be read and executed by the shell.sudo /bin/bash
This means that you callsudo
with the command/bin/bash
./bin/bash
is started as non-login shell so all the dot-files are not executed, but bash itself reads.bashrc
of the calling user. Your environment stays the same. Your home will not be root's home. So you are root, but in the environment of the calling user.sudo -s
reads the$SHELL
variable and executes the content. If$SHELL
contains/bin/bash
it invokessudo /bin/bash
(see above).Check:
To check if you are in a login shell or not (works only in bash because
shopt
is a builtin command):To look for differences you may chack the resulting environment among different invocations.
You could find some "small" differences in some critical variables:
PATH
,LD_LIBRARY_PATH
,LD_PRELOAD
or some difference in ~/. dotfiles handling (
~/.config
).Consider also the ownership of $HOME based logfiles (
~/.xsession.errors
, etc ...) or xauth cookies (~/.Xauthority
) that commands generate.Try these commands: