Need a little help with sudo understanding

I check and I did simple test with sudo and pwd and whoami commands
When I do

with
sudo su, su root, sudo -s
whoami is always = root
pwd = /home/jm/

but when I do
sudo -i pwd

Then directory = /root

So tell me please if I’m correct
If I run command with sudo -s then everything after will happen in current directory but with root privileges.
If application will save a config file it will be saved in home/user direcotry but with owned by root

If I do the same with -i then everything will be saved in “root home direcorty”

Am I correct?
If yes. What is practical usage of these parameters?

I’m asking because I need this in tutorial I’m reading. There is:
Download and extract the root filesystem (as root, not via sudo)
so should it be:
sudo - i bsdtar -xpf
or su root
then bsdtar -xpf

Yes, because in each of the above cases, you are not creating a login shell. You are merely elevating your privileges to those of the root account, while still being in the invoking user’s environment. This includes the home directory of the invoking user, as well as all environment variables set up in said account.

The bottom line is that this is a very dangerous thing to do, because you could be overwriting some of the invoking user’s files, causing them to become root-owned. An obvious example of that would be ~/.bash_history.

Yes, because if you were to look at the manual ─ heh :stuck_out_tongue: ─ then you’d see that…

sudo -i

… invokes a login shell, which means that you are effectively logging in as root and using the root account’s environment.

Note: Instead of…

su root

… it is much safer to do…

su - root

… or just…

su -

The hyphen makes it into a login shell. If you use su without the hyphen, then it’s not a login shell and then you are still within the environment of the invoking user.

Yes, that is correct.

Well, I suppose there is a practical use for it if you quickly need to elevate your privileges without leaving the environment, but I personally always recommend creating a login shell.

Note again that the first command and the second command are not equivalent. In the first command, you are creating a login shell, but in the second command, you are not.

2 Likes

So I sadly have to admit that I don’t understand what is login shell.

A login shell inherits the environment ─ i.e. the home directory, $PATH and other environment variables ─ of the account you log into. A non-login shell does not.

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.