I use less to view the text output of a command that has sensitive information. Less is good for this as it uses an alternate screen and wipes it after use. I'd like the less session to quit after a short time, like say 5 minutes.

Is there any simple command line way to invoke less with piped text and have it quit automatically after say 5 minutes?

1 Answer 1


Assuming you have GNU coreutils, a somewhat simple approach is to replace less with timeout --foreground 600 less; printf '\033[?47h'; clear; printf '\033[?1049l'; stty cooked echo in such sensitive commands. The timeout command kills a process after a given duration, the --foreground switch allows less to use the TTY, and stty cooked echo fixes the terminal after killing less. In case killing less prevented the clear and exit of the alternate screen, the intervening commands do that.

The escape sequences used in the printf commands are appropriate for a DEC-compatible terminal (emulator) such as Xterm. Your specific terminal may use different sequences to accomplish this task.

A simple function:

tless () {
  timeout --foreground 600 less "$@"
  printf '\033[?47h' # Enter alternate screen
  printf '\033[?1049l' # Exit alternate screen and restore cursor
  </dev/tty stty cooked echo # Use in a pipe requires specifying the TTY

can make for substantially less typing.

Thanks @meuh for pointing out that the original version might not clear or exit the alternate screen.

Edited to allow tless some-file. Further, this version has been tested on Linux and Solaris 11.

  • Killing less may leave the terminal in the alternate screen, showing the data. You would probably want to add a clear, and then a command to return from the alt screen, which for xterm is printf "\e[?47l"
    – meuh
    Feb 5, 2018 at 12:42
  • 1
    If you have ncurses installed, you should have a reset command which will do a “soft reset” of the terminal (which normally clears the screen and drops out of alternate view). It also does roughly the same as stty sane. Feb 5, 2018 at 14:52
  • You might be able to use the exit status to avoid the reset on normal (non-timeout, non-error) exit. Feb 5, 2018 at 15:38
  • @WillCrawford Finally got around to testing this (and made some edits). Running < somefile timeout 1 less || reset did not clear the alternate screen, but did erase the normal screen. stty sane sets the wrong erase character on my system though, so I still need to fix that ...
    – Fox
    Feb 6, 2018 at 17:02
  • Thanks. I had to adjust it a bit to make it work on BSD and MacOS as well as linux but it works. tless () { timeout 5s less "$@"; printf '\033[?47h' # Enter alternate screen; clear; printf '\033[?1049l' # Exit alternate screen and restore cursor; stty -f /dev/tty cooked echo # Use in a pipe requires specifying the TTY; }
    – k-h
    Feb 6, 2018 at 23:58

You must log in to answer this question.

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