Linux端末を使っているとき、時刻を知るためだけに
dateコマンドを実行していることが私にはよくある。これをもっと簡単にするため、端末画面の右上隅に常に時計が表示されるようにするスクリプトを作成してみた。
|
|
このスクリプトでは、ANSIエスケープシーケンス命令を使って現在のカーソル位置を保存する。次に、tputコマンドを使って、カーソルを0行(画面の一番上)の最後のカラムから19キャラクタ目(19というのは「HH:MM:SS YYYY-MM-DD」の長さである)に移動し、フォーマット指定したdateコマンドの出力を反転した緑色で表示する。そして、保存された元の位置を復元するため、別のANSIシーケンスを使ってカーソルを元の位置に戻す。
X Window Systemの端末を使っている場合、ウィンドウのサイズを変更すると時計の位置が調節される。これは、最後のカラムから19キャラクタ目に時計が表示されるようになっているためだ。ANSIエスケープシーケンスはすべての端末エミュレータで動作するわけではないが、xtermなら問題ない。スクリプトは次のとおり。
#!/bin/bash # clock.sh # the script is executed inside a while without conditions while : do # time and date are formatted to show HH:MM:SS YYYY-MM-DD cmd=`date +"%H:%M:%S %F"` # cursor's current position is saved through an escape sequence echo -n -e "\033[s" # Uncomment the next two lines to clean up the whole first line, although it causes a lot of blinking #tput cup 0 0 # positions on row 0 col 0 (left top corner) #tput el # cleans from position to end of line # to place the clock on the appropriate column, subtract the length of 'HH:MM:SS YYYY-MM-DD', which is 19, # from the total number of columns C=$((`tput cols` - 19)) tput cup 0 $C # positions cursor at row 0 col $C # clock will be shown green inverted # setaf 2 = green, smso = inverted COLOR=`tput setaf 2; tput smso` # back to normal screen colors NORMAL=`tput sgr0` # print the time-date output on the above position echo -n $COLOR$cmd$NORMAL # restore the cursor to whatever was its previous position echo -n -e "\033[u" # script is executed every second sleep 1 done
このスクリプトをclock.shとして保存し、chmodで755に設定し、「./clock.sh &」で実行する。これで時間と日付が画面の右上隅に表示されるはずだ。
clock.shを実行すると、ジョブ番号とclock.shのプロセスのプロセス識別子(PID)が端末から返される。実行中のスクリプトを終了させるには、killコマンドにジョブ番号を指定する。