Linux – Bash Prompt Below Output – Background Log Tail

bashlinuxshelltail

I used to work for a company who had a customised shell for management of one of their products that was running on Linux and I'm looking to replicate a key feature of this shell.

All the work was done by a background process and the output from the log displayed to all connected users.

The log would tail in the background to your shell, and the prompt line would always stay perfectly at the bottom.

For e.g.

Log line 1
Log line 2
Log line 3
![ROOT@PRODUCT51-LIVE]:~/ #

The way I tried to do this with bash was to start a detached tail in the users .bashrc file, but when the output from the command is sent to stdout – it comes in under the bash prompt, e.g.

![ROOT@PRODUCT51-LIVE]:~/ #Log line 1
Log line 2
Log line 3

And the user would have to press enter or CtrlC for a clean prompt line.

I'm out of ideas on how to make the prompt always jump to the bottom of the output and I think I'm using the wrong terminology to find anything on Google as I'm having no luck – does anyone know how to do this with bash?

Best Answer

The following does what you need, without using tmux or screen or other programs. Keeps the prompt at the bottom. Replace "/var/log/cron" with whatever file you need:

#!/bin/bash 
L=$(tput lines)
L1=${L}
(( L1-- ))
C=$(tput cols)
tput cup ${L} 0
tail -f /var/log/cron | while read line; do 
  tput sc
  printf "\e[1;${L1}r\e[${L1};${C}f" 
  echo; echo ${line}
  printf "\e[1;${L}r" && tput rc
done

the key to this are the ANSI control characters for the terminal. Particularly the "\e[x;y" statement which sets a new scrollable area. So, as each line of the log file is read, the bottom line in the window is excluded from the scrollable area, the line from the log file is inserted, then the bottom is added back in.