Wednesday, October 10, 2007

Shell Clock

A useful clock that is displayed inside your terminal window, it displays the time on the top right edge of your terminal :)

This is done by manipulating the terminal escape sequence, this could be done with any language but I will list here the shell script version (just to save compile effort).

We can learn about terminal escape sequences using the dtterm manual pages ($ man -s5 dtterm), here we will use the "Esc 7" (DECSC), "Esc 8" (DECRC) and "Esc [ p1 ; p2 H" sequences.

The "Esc 7" sequence is used to save cursor position, "Esc 8" is used to restore cursor position and "Esc [ p1 ; p2 H" is used to position the cursor as follows:
A p1 value 0 or 1 moves the cursor to row one. A p1 value of N moves the cursor to row N. A p2 value 0 or 1 moves the cursor to column one. A p2 value of N moves the cursor to column N.

Save the following shell code in a script called for example "clock" and run it in the background as follows

$ clock &


#! /bin/sh

while true
do
# Get time
TIME=$(date +%T)

# Save cursor position
printf "\0337"

# Set color
printf "\033[1;31m"

# Goto row 1, column 70
printf "\033[1;70H$TIME"

# Restore cursor position
printf "\0338"

sleep 1
done

0 comments: