Terminate Bash Session on Timeout

One of the lesser known features of bash is ‘$TMOUT’. When assigned a positive number this variable has two functions. When used in a script TMOUT is the timeout value for the ‘select’ command and the ‘read’ built-in.

When used in an interactive shell, and assigned a positive number, $TMOUT is the number of seconds bash will wait (after outputting the prompt) before it terminates; typically killing the users session. This is often used to ensure that unused root prompts are not left logged in for more than a minute or two without auto-closing. While this can catch a lot of people at first they soon discover that you can do a ‘TMOUT=500000’ or similar command. This is where ‘declare’ comes in.

The ‘declare’ built-in supports a number of options, the relevant one here is ‘-r’, which makes the variable read-only and immune to modification. Even by root. With a little bit of planning you can add an entry to the users profiles or login scripts that they can’t touch and will ensure that their sessions don’t stay logged in when they’re not using them.