SourceForge.JP: Open Source Software

LoginCreate AccountAdd BookmarkHelp

OpenSource Downloads

(7,661) Cabos
(2,622) 7-Zip
(1,956) HandBrake Japanese Language Version
(1,671) CrystalDiskInfo
(1,621) Tera Term
(1,111) CrystalDiskMark
(827) ffdshow
(589) Tween
(586) ギコナビ
10  (542) Amateras
11  (495) VirtualDubMod-jp
12  (460) NNDD - ニコニコ動画DL&再生ソフト
13  (456) MergeDoc
14  (437) SMPlayer
15  (401) えこでこツール
More >>

最近ブックマークされた記事

CLIマジック:ANSIエスケープシーケンスを使って端末に時計を表示する

2008年01月24日 10:56 1 2
  • スラッシュドットにタレコむ
  • あとで読む
 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コマンドにジョブ番号を指定する。

Sergio-Gonzalez-Duran(2008年1月22日(火))
2008年03月25日 17:07 更新