2

I logged in to Debian 7 via SSH, not as root. When writing sudo all the time became too much overhead, I did sudo su. Since the Debian default shell (dash ?) does not support the Tab key to complete filenames, I ran /bin/bash. I added a few aliases to .bash_aliases and to activate them, I ran /bin/bash again (potentially a few more times) until I got all aliases right.

After doing some more system setup, I could not remember any more how many times I have to type exit to get back to the beginning but not logging out from SSH.

Actually this is not a big deal, since I could log in via SSH again, so this is more an academic question. I wondered if there is a way to find out

  1. what exactly exit will exit, so I could at least check each time before I type it
  2. how many times I can exit until the user is logged out completely

I tried man exit but it seems there is no manual available. help exit doesn't tell much either.

I first thought I could find a possible solution using pstree, but IMHO it lists sshd too often and sudo su is missing.

:~$ pstree | grep ssh
     |-sshd---sshd---sshd---sh---bash---bash-+-grep
1
  • 1
    exit is a shell builtin. So man exit will not work, as there is no man page for it.
    – s3lph
    Jun 19, 2015 at 22:45

2 Answers 2

3

You can use the SHLVL variable to determine how far nested in you're, to a shell started by a login process:

$ echo $SHLVL 
1
$ bash
$ echo $SHLVL 
2
$ bash
$ echo $SHLVL 
3
$ sudo su -            # Start a login shell, clears $SHLVL
# echo $SHLVL 
1
# logout
$ sudo su
# echo $SHLVL 
4
# bash
# echo $SHLVL 
5

Since the login shell from su - clears SHLVL, it has SHLVL=1. To quit the nearest such login shell in the shell ancestry, you have to use exit $SHLVL times.


SHLVL is not supported by dash, so whenever it enters the picture, the figure will be wrong. However, dash isn't the login shell for any usable account on Ubuntu, and SHLVL works on more advanced shells like bash and zsh.


I cannot reproduce your missing sudo su:

$ pstree -ps $$
init(1)───sshd(1404)───sshd(12614)───sshd(12673)───zsh(12674)───sudo(31012)───su(31014)───bash(31016)───pstree(31084)
1
  • To add to what @muru had to say, this will also count screen sessions.
    – jfreak53
    Jun 20, 2015 at 3:04
1

You can simply use the command ps with no arguments. Here I have 3 nested bashes so 3 exits to type:

~ $ ps
  PID TTY          TIME CMD
 1986 pts/2    00:00:10 bash
31351 pts/2    00:00:00 bash
31399 pts/2    00:00:00 bash
31450 pts/2    00:00:00 ps
2
  • What about sudo su? And what if my ps list is very long? Jun 20, 2015 at 10:30
  • sudo and su both appear. You need to ignore the sudo in the count though.
    – meuh
    Jun 20, 2015 at 10:34

You must log in to answer this question.

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