What are the implications of nested "su" command calls in a shell?

692 Views Asked by At

When I open a windows shell and write su to be a root user, I notice that I can write su again, and again, and again... If I write exit then this lead me to the previous "su instance" (?), and I have to write as many exit as su I wrote. What are the implications of this multiple "instances" and are there any advantages of this behaviuor?

3

There are 3 best solutions below

0
On

Each time you run the su command a new shell opens inside the current shell.

To exit a shell you run exit.

0
On

When you execute su, you are going to create a subprocess (child process) of the parent shell. If you run bash (or zsh) in a shell, the meaning it's the same.

If you want to know the level of your current subshell just run echo $SHLVL.

Simply, when you run su multiple times, you are creating a family of process.

2
On

Within the Unix programming model, there is no way for a user process to gain the privileges of root or another user.

This means that it's not possible to write a version of su that simply turns your current shell into a root shell. Instead, you have to get root access by running a suid executable, and that necessarily creates a new instance.

There's no specific advantage, it just happens to be the only way to implement su in traditional Unix.

You can choose to use exec su instead of su to replace your current shell with the new instance. This means that exit in the root shell will simply log you out.

However, I would recommend just going with it. If you exit vim or nano, you expect to go back to your original shell. If you exit ssh, you expect to go back to your original shell. Don't try to make su an exception.