5

Like title says, is there a difference between these two commands :

sudo su - root
sudo -u root -H /bin/bash

I'm using GNU/Linux, if that makes a difference.

0

4 Answers 4

9

If you want to become root, the best way to do so is sudo -i, which simulates the initial login (giving you all the paths and variables associated with a root login). If you want to login without getting the root users .files, you could just use sudo su (no need to specify the root user).

3
  • sudo -H /bin/bash does run bash. The -H option doesn't take an argument. Commented Mar 21, 2012 at 23:37
  • -H just changes the $HOME to the target user's home directory. That's it. As the man page says, this might even be the default policy.
    – jsbillings
    Commented Mar 22, 2012 at 0:11
  • is there a source for this solution please?
    – Thufir
    Commented Apr 29, 2020 at 4:10
7
su - # causes the user to run a login shell aka bash --login
     # the same as if the user had logged in as the root from the login prompt

and sudo su - is the same as sudo su - root specifying root is redundant.

sudo -u root -H /bin/bash again the -u root is redundant, sudo runs as root by default but the -H /bin/bash is run as an sudoer, the env vars SUDO_USER, SUDO_UID and SUDO_COMMAND are set to the callers name/uid and bash respectively.

But in this case, bash is not run as a login shell.

3

Obviously, they can differ if root shell isn't /bin/bash - this is possible for tiny or embedded Linux environments, or traditional for BSD systems which prefer /bin/[t]csh for root user. Also, `su -' drops all environment except a few variables related to the terminal. sudo's behavior on environment is configurable (see env_reset in /etc/sudoers). So, be careful with details...

1

The biggest difference between the two commands you listed is that running su - will cause the shell to be a login shell. That means that root's shell's login scripts will be executed (.bash_profile for example, if it's bash), the PWD will be set to $HOME, and certain parts of the user environment will be initialized. sudo bash just runs a new shell as the target user's shell, and the -H just initializes one variable, $HOME, to the target user's home directory. Other variables will not be set, and some will be carried over to the new shell, as defined in your sudo policy.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .