Icon of a thin page Icon of a thick page

Bash Upon Entering and Exiting

David A. Harding

Two things annoyed me yesterday:

  1. Starting a new shell and forgetting to connect to an existing screen session
  2. Forgetting to invalidate a sudo passwordless login before closing a shell

Fixing these problems though automation is easy with a bit shell magic.


Check for screen
screen is a very talented program that makes dealing with many shells—particularly shells on remote computers—convient. If you don't know what screen is, I suggest you learn about it before continuing or you skip this section.

I derive more benefits from screen the earlier I connect to an existing session after opening a shell. The following code, added to my $HOME/.bashrc, notifies me of existing screen sessions when I login (or start a non-login shell):

        if [ -x /usr/bin/screen ]
        then
                screen -q -ls
                if [ "$?" -ge 10 -a "$TERM" != screen ]
                then
                        echo "There is a screen session running"
                fi
        fi

For documentation on screen's behaviour as used above, see the screen(1) manual description of the -q option.


Dump Passwordless sudo Access
On many systems, by default, sudo only requires you to provide your user password if you haven't used sudo in 5 minutes. I think this feature is convient but I always feel uncomfortable when I close a shell I recently ran sudo in, open another shell, and can still run sudo without entering my password. I don't think the following shell code increases security, but it makes me comfortable knowing my passwordless sudo access dies with the shell.

        function _exit()
        {
                if [ -x /usr/bin/sudo ]
                then
                        sudo -k
                fi
        }
        trap _exit 0

See the sudo(8) manual's description of the -k switch and the bash(1) manual or info pages (or run help trap) for a description of trap.


Notes and Links

  1. I've configured my shell to source (execute in the current environment) my $HOME/.bashrc every time I run a bash shell.
  2. I've slightly modified the code samples above from what appears in my $HOME/.bashrc (below)
  3. My .bashrc
  4. This is my first time using highlight for syntax highlighting in the XHTML displayed on my blog. I like the tool and plan to use it again.