Disconnecting Inactive Sessions

Problem

You’d like to be able to automatically log out inactive users, especially root.

Solution

Set the $TMOUT environment variable in /etc/bashrc or ~/.bashrc to the number of seconds of inactivity before ending the session. In interactive mode, once a prompt is issued, if the user does not enter a command in $TMOUT seconds, bash will exit.

Discussion

$TMOUT is also used in the read built-in and the select command in scripts.

Don’t forget to set this as a read-only variable in a system-level file such as /etc/profile or /etc/bashrc to which users have no write access if you don’t want them to be able to change it.

declare -r TMOUT=3600

# Or:
readonly TMOUT=3600

Warning

Since the user has control over their own environment, you cannot totally rely on $TMOUT, even if you set it as read-only, since the user could just run a different shell. Think of it as a helpful reminder to cooperative users, especially knowledgeable and interrupt-driven system administrators who may get distracted (constantly).

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.