Two parts to this answer, both reliant on editing the sudoers
file. (I'm not sure how to answer this with POSIX compliance as neither sudo
nor bash
used in your example are POSIX. However, the solution should be portable across systems that use these tools.)
You can simplify your use of sudo
and avoid the alias by setting the boolean variable shell_noargs
in the /etc/sudoers
file. You can now use sudo
to access a root shell instead of sudo -s
.
Some shells such as bash
allow you to keep track of the shell level through a variable such as $SHLVL
. This can be tracked through sudo
invocations as well as through simply typing bash
. Adding this to your shell prompt will help you identify how many levels of nesting you currently have.
Create our own sudoers
file rather than editing the system-provided one:
sudo EDITOR=nano visudo -f /etc/sudoers.d/local
Add these lines to the file and save it
# Allow sudo with no args to create a shell
Defaults shell_noargs
# Allow bash to share its nesting level
Defaults env_check+="SHLVL"
For bash
, go to your ~/.bashrc
(and maybe either ~/.bash_profile
or ~/.profile
) and find the line that defines PS1
. Modify it to include $SHLVL
. For example, on my Debian system it's set like this:
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\W\$ '
I would modify it to include $SHLVL
like this:
PS1='${debian_chroot:+($debian_chroot)}\u@\h[$SHLVL]:\W\$ '
Finally, repeat the edit for root's configuration file(s).
Note, if you're using a shell other than bash
that does not provide $SHLVL
it's trivial to implement provided that the shell runs a configuration file each time it starts. (POSIX sh
does not, unfortunately.)