Bash Prompt HOWTO <author> Giles Orr, <htmlurl url="mailto:giles@interlog.com" name="giles@interlog.com"> <date>$Revision: 1.3 $, $Date: 2001/09/07 17:04:58 $ <trans>遠藤 明 <akendo@t3.rim.or.jp> <tdate>v0.60j, 19 January 1999 <!-- CHANGELOG: $Log: Bash-Prompt-HOWTO.sgml,v $ Revision 1.3 2001/09/07 17:04:58 senda マークアップのミスを修正, yuji senda Revision 1.2 2000/05/12 15:15:28 nakano LINUXDOCTR_2000_05_09 branch merge: migration to linuxdoctr DTD for translation docs Revision 1.1.2.1 2000/05/09 12:51:03 nakano linuxdoc->linuxdoctr Revision 1.1 1999/02/26 17:09:38 morimoto Bash-Prompt/Bash-Prompt-HOWTO.sgml -> Bash-Prompt-HOWTO/Bash-Prompt-HOWTO.sgml Revision 1.1.1.1 1999/02/22 19:20:40 baba Revision 0.60 1999/01/07 02:10:28 giles Very minor cosmetic changes. Forced revision 0.60. Revision 0.57 1999/01/07 01:37:35 giles Changed to code environment where appropriate. Minor cosmetic changes. Revision 0.56 1999/01/07 01:05:50 giles Added "Copyright and Disclaimer," added Johan's note. Some other minor changes. -> RCS is unhappy with me because I moved the HOWTO between the laptop and the desktop: slight shift in the numbering scheme. Revision 0.58 1998/12/25 04:35:31 giles Corrected minor readability issues. Look out for tabs in pasted scripts: this continues to be a problem. Revision 0.57 1998/12/25 04:13:57 giles Replaced esc0, esc1, esc2, and esc3 with one escgen script. Added colour echoing script. Revision 0.56 1998/12/23 05:25:13 giles Added some minor revisions. Added Torben's "jobcount" in the prompt suggestion. Added section on ANSI cursor movement. Revision 0.55 1998/12/01 12:22:48 giles Clean-up in preparation for public release. --> <abstract> <!-- Creating and controlling terminal and xterm prompts is discussed, including incorporating standard escape sequences to give username, current working directory, time, etc. Further suggestions are made on how to modify xterm title bars, use external functions to provide prompt information, and how to use ANSI colours. --> 端末と xterm でのプロンプトの作成と制御の解説で、ユーザー名、現在の ディレクトリ、時間などを表示する標準のエスケープ・シーケンスを含んで います。xterm のタイトルバーを変えたり、プロンプトに外部関数を使った 情報をいれたり、ANSI カラーを使う方法も述べます。 </abstract> <toc> <sect><!--Introduction and Administrivia-->はじめに、 <sect1><!--Requirements-->前提 <p> <!-- You will need Bash. The default version on almost all Linux distributions is 1.14.7 (as of this writing, November 98), which is a well known and reliable shell. Bash is now available in version 2.0+: I've been using Bash 2.0 for a while now, but almost all code presented here should work under 1.14.7. If I'm aware of a problem, I'll mention it. You can check your Bash version by typing <TT>echo $BASH_VERSION</TT> at the prompt. On my machine, it responds with <TT>2.02.1(1)-release</TT>. --> Bash が必要です。ほとんどの Linux についてくるバージョンは(これを書いている 98年11月時点で)1.14.7で、有名で、信頼性の高いシェルです。 Bash のバージョンは、現在 2.0 以上になっており、私はここしばらく Bash 2.0 を 使っていますが、ここで示したほとんどのコードは1.14.7でも動きます。 何か問題のあるところは、私が知っている限り、指摘しておきました。 あなたの Bash のバージョンは、<TT>echo $BASH_VERSION</TT>とプロンプトで タイプすると分かります。私の機械では、<TT>2.02.1(1)-release</TT>となります。 <p> <!-- Shell programming experience would be good, but isn't essential: the more you know, the more complex prompts you'll be able to create. I assume a basic knowledge of shell programming and Unix utilities as I go through this tutorial. However, my own shell programming skills are limited, so I give a lot of examples and explanation that may appear unnecessary to an experienced shell programmer. --> シェル・プログラミングの経験は有用ですが、必須ではありません。 知識が多ければ多いほど、より複雑なプロンプトをつくれることでしょう。 このチュートリアルを読むのに、シェル・プログラミングと Unix ツールの 基本的な知識を仮定しましたが、そもそも私のシェル・プログラミングの 知識は限定されたものですから、私は、沢山の例や説明を書きましたが、 それらは経験を積んだシェル・プログラマには不必要に思えるかもしれません。 <sect1><!--How To Use This Document-->このドキュメントの使い方 <p> <!-- I include a lot of examples and explanatory text. Different parts will be of varying usefulness to different people. This has grown long enough that reading it straight through would be difficult - just read the sections you need, backtrack as necessary. --> 例や説明を多くいれました。読む人が変われば、どの部分が役に立つと思うかも 変わってくるでしょう。大きな文書になってきましたので、最初から通して読む ことが難しくなってきています。読みたいところを拾い読みし、必要に応じて 戻って下さい。 <sect1><!--Translations-->翻訳 <p> <!-- As I write (6 January 99), translations are under weigh to both Japanese (Akira Endo, <htmlurl url="mailto:akendo@t3.rim.or.jp" name="akendo@t3.rim.or.jp">) and German (Thomas Keil, <htmlurl url="mailto:thomas@h-preissler.de" name="thomas@h-preissler.de">). Many thanks to both of them! URLs will be included when they become available. --> 現在(1999年1月6日)、 日本語(Akira Endo, <htmlurl url="mailto:akendo@t3.rim.or.jp" name="akendo@t3.rim.or.jp">)とドイツ語(Thomas Keil, <htmlurl url="mailto:thomas@h-preissler.de" name="thomas@h-preissler.de">) への翻訳が進められています。お二人に感謝。URLが入手できたらつけ加えます。 <sect1><!--Problems-->問題 <p> <!-- This is a list of problems I've noticed while programming prompts. Don't start reading here, and don't let this list discourage you - these are mostly quite minor details. Just check back if you run into anything odd. --> これは、私がプロンプトをプログラムしていて気がついた問題点のリストです。 ここから読み始めてがっかりしないで下さい。これは細かな小さな問題です。 何か変なことが起こった時にここに戻って下さい。 <itemize> <item> <!-- Many Bash features (such as math within $(()) among others) are compile time options. If you're using a binary distribution such as comes with an standard Linux distribution, all such features should be compiled in. But if you're working on someone else's system, this is worth keeping in mind if something you expected to work doesn't. Some notes about this in <em>Learning the Bash Shell</em>, p.260-262. --> 多くの Bash の機能(たとえば$(())の中での計算)は、コンパイル時のオプションです。 標準の Linux ディストリビューションにはいってくるもののように、バイナリーの Bash を使っているなら、このような機能はすべてコンパイルされているものと 思います。しかし、もし他人のシステムで仕事をしているなら、期待していることが うまくいかなかった場合にこのことを思い出して下さい。これについては、 <em>Learning the Bash Shell</em>, p.260-262に記載があります。 <item> <!-- The terminal screen manager "screen" doesn't always get along with ANSI colours. I'm not a screen expert, unfortunately. My current version of screen (a very recent one) seems to work well in all cases, but I've seen occasions where screen reduced all prompt colours to the standard foreground colour in X terminals. This doesn't appear to be a problem on the console. --> 端末のスクリーンマネージャー"screen"は、必ずしもANSIカラーをサポートして いるとは限りません。残念ながら私は screen についてそれほど詳しくありません。 私の screen のバージョンは非常に新しいもので、すべての場合にうまくいって いますが、X 端末上で、プロンプトの色が標準のフォアグラウンドカラー一色に なってしまうことがありました。このようなことはコンソールでは生じないようです。 <item> <!-- Xdefaults files can override colours. Look in ~/.Xdefaults for lines referring to XTerm*background and XTerm*foreground (or possibly XTerm*Background and XTerm*Foreground). --> Xdefaults ファイルで色を変えていることがあります。~/.Xdefaults の中で、 XTerm*background や XTerm*foreground (あるいは XTerm*Background や XTerm*Foreground) の記述がないか調べて下さい。 <item> <!-- One of the prompts mentioned in this document uses the output of "jobs" - as discussed at that time, "jobs" output to a pipe is broken in Bash 2.02. --> この文書の中で"jobs"の出力を使っているプロンプトがあり、そこで述べますが、 Bash 2.02 では、"jobs"の出力をパイプに渡すところがうまくいきません。 <item> <!-- ANSI cursor movement escape sequences aren't all implemented in all X terminals. That's discussed in its own section. --> ANSI カーソル操作シーケンスは、すべてのX端末で実現されているわけでは ありません。その章で述べます。 <item> <!-- Some nice looking pseudo-graphics can be created by using a VGA font rather than standard Linux fonts. Unfortunately, these effects look awful if you don't use a VGA font, and there's no way to detect within a term what kind of font it's using. --> 見栄えのする疑似グラフィックは、Linux 標準のフォントではなく、VGA フォントに よって表示されます。残念ながらこれは VGA フォントを使わないとひどい姿になり ます。またどんなフォントを使っているかを端末の中で調べる方法がありません。 <item> <!-- Bash 2.0+ is out, and it incorporates some new features, and changes some behaviour. Things that work under 1.14.7 don't necessarily work the same under 2.0+, or vice versa. --> Bash 2.0+ が出されており、新しい機能が付加され、ある機能のふるまいが異なって います。1.14.7で動いていたものが2.0+で動かなかったり、 また逆の場合があり得ます。 </itemize> <sect1><!--Send Me Comments and Suggestions-->コメントや提案を聞かせてください <p> <!-- This is a learning experience for me. I've come to know a fair bit about what can be done to create interesting and useful Bash Prompts, but I need your input to correct and improve this document. I've tried to check suggestions I make against different versions of Bash (mostly 2.02, which I use, and 1.14.7, which is in wide use), but let me know of any incompatibilities you find. <p> The latest version of this document should always be available at <htmlurl url="http://www.interlog.com/~giles/bashprompt.html" name="http://www.interlog.com/~giles/bashprompt.html">. Please check this out, and feel free to e-mail me at <htmlurl url="mailto:giles@interlog.com" name="giles@interlog.com"> with suggestions. --> これを書くことが私にとっての勉強にもなりました。興味深い役に立つ Bash プロンプトを書くことができるようになりました。 でも、この文書の誤りを直し、改善していくには、あなたからの感想が必要です。 私の示したものをバージョンの異なる Bash (多くは私が使っている2.02で、また 広く使われている1.14.7でも)でチェックしてみましたが、何か不都合な点が あれば知らせて下さい。 <p> この文書の最新版は <htmlurl url="http://www.interlog.com/~giles/bashprompt.html" name="http://www.interlog.com/~giles/bashprompt.html"> から入手可能ですので、ここをチェックして下さい。そして、私 <htmlurl url="mailto:giles@interlog.com" name="giles@interlog.com">に 気軽に e-mail を送り、ご意見をお聞かせ下さい。 <p> <!-- I use the Linux Documentation Project HOWTOs almost exclusively in the HTML format, so when I convert this from SGML, HTML is the only format I check thoroughly. If there are problems with other formats, I may not know about them, and I'd appreciate a note about them. --> 私は LDP の HOWTO をほとんど HTML フォーマットで使っています。 したがって、この文書を SGML から変換してよくチェックしたのは、HTML だけです。他のフォーマットで 問題があっても分かりませんので、知らせていただければ幸いです。 <sect1><!--Credits-->謝辞 <p> <!-- In producing this document, I have borrowed heavily from the work of the Bashprompt project at <htmlurl url="http://bash.current.nu/" name="http://bash.current.nu/">. Other sources used include the <em>xterm Title mini-HOWTO</em> by Ric Lister, available at <htmlurl url="http://sunsite.unc.edu/LDP/HOWTO/mini/Xterm-Title.html" name="http://sunsite.unc.edu/LDP/HOWTO/mini/Xterm-Title.html">, <em>Ansi Prompts</em> by Keebler, available at <htmlurl url="http://www.ncal.verio.com/~keebler/ansi.html" name="http://www.ncal.verio.com/~keebler/ansi.html">, <em>How to make a Bash Prompt Theme</em> by Stephen Webb, available at <htmlurl url="http://bash.current.nu/bash/HOWTO.html" name="http://bash.current.nu/bash/HOWTO.html">, and <em>X ANSI Fonts</em> by Stumpy, available at <htmlurl url="http://home.earthlink.net/~us5zahns/enl/ansifont.html" name="http://home.earthlink.net/~us5zahns/enl/ansifont.html">. --> この文書を書くために <htmlurl url="http://bash.current.nu/" name="http://bash.current.nu/"> の Bashprompt プロジェクトから非常に多くのものを借りました。 その他、 <htmlurl url="http://sunsite.unc.edu/LDP/HOWTO/mini/Xterm-Title.html" name="http://sunsite.unc.edu/LDP/HOWTO/mini/Xterm-Title.html">で入手 可能な Ric Lister による<em>xterm Title mini-HOWTO</em>、 <htmlurl url="http://www.ncal.verio.com/~keebler/ansi.html" name="http://www.ncal.verio.com/~keebler/ansi.html">で入手可能な Keebler による<em>Ansi Prompts</em>、 <htmlurl url="http://bash.current.nu/bash/HOWTO.html" name="http://bash.current.nu/bash/HOWTO.html">で入手可能な Stephen Webb による<em>How to make a Bash Prompt Theme</em>、 <htmlurl url="http://home.earthlink.net/~us5zahns/enl/ansifont.html" name="http://home.earthlink.net/~us5zahns/enl/ansifont.html">で入手可能な Stumpyによる<em>X ANSI Fonts</em>もためになりました。 <p> <!-- Also of immense help were several conversations and e-mails from Dan, a co-worker at Georgia College & State University, whose knowledge of Unix far exceeds mine. He's given me several excellent suggestions, and ideas of his have led to some interesting prompts. --> 私よりずっと深い Unix の知識を持つ Georgia College & State University の 同僚 Dan からの e-mail も助けになりました。多くの素晴らしい提案をしてくれ、 また彼の考えによっておもしろいプロンプトができました。 <p> <!-- Three books that have been very useful while programming prompts are <em>Linux in a Nutshell</em> Jessica Heckman Perry (O'Reilly, 1997), <em>Learning the Bash Shell</em> Cameron Newham and Bill Rosenblatt (O'Reilly, 2nd. ed., 1998) and <em>Unix Shell Programming</em> Lowell Jay Arthur (Wiley, 1986. This is the first edition, the fourth came out in 1997). --> プロンプトをプログラムするために、3冊の本がとても役に立ちました。 <em>Linux in a Nutshell</em> Jessica Heckman Perry (O'Reilly, 1997)、 <em>Learning the Bash Shell</em> Cameron Newham and Bill Rosenblatt (O'Reilly, 2nd. ed., 1998)、 <em>Unix Shell Programming</em> Lowell Jay Arthur (Wiley, 1986、これは第1版で 第4版が1997年にでました)です。 <sect1><!--Copyright and Disclaimer-->著作権と責任放棄 <p> This document is copyright 1998-1999 by Giles Orr. You are encouraged to redistribute it. You may not modify this document (see the section on contacting me: I have so far been incorporating all changes recommended by readers). Please contact me if you're interested in doing a translation: that's one modification I can live with. この文書の著作権は、Giles Orr、1998-1999 が有しています。どうぞ再配布を お願いします。この文書を改変してはなりません(私へのコンタクトの章を読んで 下さい。これまで読者から受けた提案はこの中に含めてあります)。翻訳したい 方は私にコンタクトして下さい。これが私の許可する唯一の改変です。 <p> This document is available for free, and, while I have done the best I can to make it accurate and up to date, I take no responsibility for any problems you may encounter resulting from the use of this document. この文書は無料で入手できます。できるだけ正確で最新のものにしたつもりですが、 この文書を使用してあなたが遭遇するどんな問題にも責任はとりません。 <sect><!--Bash and Bash Prompts-->BashとBashのプロンプト <sect1><!--What is Bash? -->Bashとは <p> <!-- Descended from the Bourne Shell, Bash is a GNU product, the "<bf>B</bf>ourne <bf>A</bf>gain <bf>SH</bf>ell." It's the standard command line interface on most Linux machines. It excels at interactivity, supporting command line editing, completion, and recall. It also supports configurable prompts - most people realize this, but don't know how much can be done. --> Bourne Shell の流れをくむ Bash は、GNU で開発されており、 <bf>B</bf>ourne <bf>A</bf>gain <bf>SH</bf>ell から名付けられています。 多くの Linux では標準のコマンドライン・インターフェースになっています。 対話性や、コマンドラインの編集、補完、履歴といった機能に卓越しています。 プロンプトを設定変更できることは多くの人が知っていますが、 どこまでのことができるかはあまり知られていません。 <sect1><!--What can tweaking your Bash Prompt do for you?-->Bash プロンプトをいじるとよいことがあるのですか? <p> <!-- Most Linux systems have a default prompt in one colour (usually gray) that tells you your user name, the name of the machine you're working on, and some indication of your current working directory. This is all useful information, but you can do much more with the prompt: all sorts of information can be displayed (tty number, time, date, load, number of users, uptime ...) and the prompt can use ANSI colours, either to make it look interesting, or to make certain information stand out. You can also manipulate the title bar of an Xterm to reflect some of this information. --> 多くの Linux のデフォルトのプロンプトは、1色(通常グレイ)で、ユーザー名、 マシン名、現在のディレクトリを示すものになっています。これは役に立つ 情報です。でもプロンプトはもっと多くのことを示せます。どんな情報でも 示すことができます。tty 番号、時間、日付、負荷状態、ユーザー数、接続時間等々。 プロンプトには ANSI の色が使え、見た目を面白くしたり、ある情報を際立たせたり できます。 このような情報を示すために、Xterm のタイトルバーを操作することもできます。 <sect1><!--Why bother?-->なぜ面倒なことをするの? <p> <!-- Beyond looking cool, it's often useful to keep track of system information. One idea that I know appeals to some people is that it makes it possible to put prompts on different machines in different colours. If you have several Xterms open on several different machines, or if you tend to forget what machine you're working on and delete the wrong files, you'll find this a great way to remember what machine you're on. --> かっこよく見せるというだけでなく、システム情報が示されるのは役に立つこと が多いでしょう。 異なった機械では異なった色でプロンプトを出すというようなことに使う 人もいます。いくつもの Xterm をいくつもの機械で動かしていたり、どの機械を 動かしているのかを勘違いして、間違ったファイルを削除したりするような人は、 このような工夫をすることによって、どの機械を動かしているかを忘れる ことがなくなるでしょう。 <sect1><!--The First Step-->第一段階 <p> <!-- The appearance of the prompt is governed by the shell variable PS1. Command continuations are indicated by the PS2 string, which can be modified in exactly the same ways discussed here - since controlling it is exactly the same, and it isn't as "interesting," I'll mostly be modifying the PS1 string. (There are also PS3 and PS4 strings. These are never seen by the average user - see the Bash man page if you're interested in their purpose.) To change the way the prompt looks, you change the PS1 variable. For experimentation purposes, you can enter the PS1 strings directly at the prompt, and see the results immediately (this only affects your current session, and the changes go away when you log out). If you want to make a change to the prompt permanent, modify your ~/.bashrc file, and add the new definition of PS1 there. If you have root permissions, you can look in /etc/profile and modify the "<bf>PS1=</bf>" line. Be aware that on some distributions (RedHat 5.1 at least) that the /etc/bashrc overrides the setting of the PS1 and PS2 strings. --> プロンプトの形状はシェル変数 PS1 によって決まります。 コマンドが2行以上になる時の2行目以降のプロンプトは、PS2 の文字列で 決まります。これは PS1 と全く同じ書き方ですので、この文書ではほとんど PS1 についてだけ述べます。(PS3 と PS4 という変数もあります。これらは 通常のユーザーが見ることはありません。もし興味があれば、Bash の man ページを見てください。)プロンプトを変えるには、PS1 を変えます。 実験してみるには、PS1 の文字列を直接プロンプトのところで変えてみて 下さい。結果がすぐに表れるでしょう。 (この変化は現在の環境を変えるだけで、ログアウトすれば なくなってしまいます。) もしプロンプトを永久に変えたければ、~/.bashrc に PS1 の新しい定義を 置いて下さい。もし、ルート権限を持っているなら、/etc/profile ファイルの 中の"<bf>PS1=</bf>"の行を変えます。Linux のディストリビューションの種類に よっては(RedHat 5.1ではそうですが)/etc/bashrc が PS1 と PS2 の設定を 変えますので、注意してください。 <p> <!-- Before we get started, it's important to remember that the PS1 string is stored in the environment like any other environment variable. If you modify it at the command line, your prompt will change. Before you make any changes, you can save your current prompt to another environment variable: --> はじめに注意しておきますが、PS1 の設定は他の環境変数と同様、環境に保存されて います。PS1 の設定をコマンドラインで変化させれば、プロンプトが変わります。 変更する前に現在のプロンプトを保存したければ、別の環境変数に保存しておいて ください。 <verb> [giles@nikola giles]$ SAVE=$PS1 [giles@nikola giles]$ </verb> <p> <!-- The simplest prompt would be a single character, such as: --> もっとも簡単なプロンプトは1文字からなるものです。たとえば <verb> [giles@nikola giles]$ PS1=$ $ls bin mail $ </verb> <p> <!-- This demonstrates the best way to experiment with basic prompts, entering them at the command line. Notice that the text entered by the user appears immediately after the prompt: I prefer to use --> 簡単なプロンプトを実験するには、このようにコマンドラインで入れます。 ユーザーが入力する文字がプロンプトの直後に表れることに注意して下さい。 私は次のようにプロンプトを設定する方が好きです。 <verb> $PS1="$ " $ ls bin mail $ </verb> <p> <!-- which forces a space after the prompt, making it more readable. To restore your original prompt, just call up the variable you stored: --> こうすることによって、プロンプトの次にスペースが置かれ、読みやすくなります。 もとのプロンプトに戻すには、保存しておいた変数を呼び出します。 <verb> $ PS1=$SAVE [giles@nikola giles]$ </verb> <sect1><!--Bash Prompt Escape Sequences-->Bashプロンプトのエスケープシーケンス <p> <!-- There are a lot of escape sequences offered by the Bash shell for insertion in the prompt. From the Bash 2.02 man page: --> Bash には、プロンプトで使えるエスケープシーケンスが沢山あります。 Bash 2.02 の man ページをみると、 <!-- <verb> When executing interactively, bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when it needs more input to complete a command. Bash allows these prompt strings to be cus- tomized by inserting a number of backslash-escaped special characters that are decoded as follows: \a an ASCII bell character (07) \d the date in "Weekday Month Date" format (e.g., "Tue May 26") \e an ASCII escape character (033) \h the hostname up to the first `.' \H the hostname \n newline \r carriage return \s the name of the shell, the basename of $0 (the portion following the final slash) \t the current time in 24-hour HH:MM:SS format \T the current time in 12-hour HH:MM:SS format \@ the current time in 12-hour am/pm format \u the username of the current user \v the version of bash (e.g., 2.00) \V the release of bash, version + patchlevel (e.g., 2.00.0) \w the current working directory \W the basename of the current working direc- tory \! the history number of this command \# the command number of this command \$ if the effective UID is 0, a #, otherwise a $ \nnn the character corresponding to the octal number nnn \\ a backslash \[ begin a sequence of non-printing characters, which could be used to embed a terminal con- trol sequence into the prompt \] end a sequence of non-printing characters </verb> --> <verb> 対話型で実行される時には、bash はコマンド待ちの状態で、一次 プロンプトの PS1 を表示し、コマンドを完成するのにさらに入力が 必要な時には二次プロンプトの PS2 を表示します。bash ではバック スラッシュでエスケープした文字を挿入することにより、プロン プトを修飾することができます。その意味は次のとおりです。 \a ASCII のベル文字 (07) \d "曜日 月 日"のフォーマットによる日付け (例 "Tue May 26") \e ASCII のエスケープ文字 (033) \h 最初の"."のところまでのホスト名 \H ホスト名 \n 改行 \r 復帰 \s シェル名、$0 のベース名 (最後のスラッシュの後ろの部分) \t 24時間制の HH:MM:SS のフォーマットによる時間 \T 12時間制の HH:MM:SS のフォーマットによる時間 \@ am/pm をつけた12時間制のフォーマットによる時間 \u 現ユーザーのユーザー名 \v bash のバージョン(例 2.00) \V bash のリリース番号、バージョンとパッチレベル (例 2.00.0) \w 現在のディレクトリ \W 現在のディレクトリのベース名 \! 現在のコマンドのヒストリー番号 \# 現在のコマンドのコマンド番号 \$ UIDが0なら#、そうでなければ$ \nnn 8進数nnnに対応する文字 \\ バックスラッシュ \[ 表示されない文字列の開始。端末制御シーケンスを プロンプトに埋め込む。 \] 表示されない文字列の終り。 </verb> <p> <!-- Continuing where we left off: --> それでは続きです。 <verb> [giles@nikola giles]$ PS1="\u@\h \W> " giles@nikola giles> ls bin mail giles@nikola giles> </verb> <p> <!-- This is similar to the default on most Linux distributions. I wanted a slightly different appearance, so I changed this to: --> これはデフォルトのプロンプトとほとんど変わりありません。そこで少し スタイルを変えてみましょう。 <verb> giles@nikola giles> PS1="[\t][\u@\h:\w]\$ " [21:52:01][giles@nikola:~]$ ls bin mail [21:52:15][giles@nikola:~]$ </verb> <sect1><!--Setting the PS? Strings Permanently-->PS?文字列の設定を永続させる<label id="setps"> <p> <!-- Various people and distributions set their PS? strings in different places. The most common places are /etc/profile, /etc/bashrc, ~/.bash_profile, and ~/.bashrc . Johan Kullstam (<htmlurl url="mailto:johan19@idt.net" name="johan19@idt.net">) writes: --> 多くの人、多くのディストリビューションが PS? 文字列を異なったところで 設定しています。一番多いのは、/etc/profile、/etc/bashrc、~/.bash_profile 及び~/.bashrcです。Johan Kullstam (<htmlurl url="mailto:johan19@idt.net" name="johan19@idt.net">)は書いています。 <!-- <tscreen><verb> the PS1 string should be set in .bashrc. this is because non-interactive bashes go out of their way to unset PS1. the bash man page tells how the presence or absence of PS1 is a good way of knowing whether one is in an interactive vs non-interactive (ie script) bash session. the way i realized this is that startx is a bash script. what this means is, startx will wipe out your prompt. when you set PS1 in .profile (or .bash_profile), login at console, fire up X via startx, your PS1 gets nuked in the process leaving you with the default prompt. one workaround is to launch xterms and rxvts with the -ls option to force them to read .profile. but any time a shell is called via a non-interactive shell-script middleman PS1 is lost. system(3) uses sh -c which if sh is bash will kill PS1. a better way is to place the PS1 definition in .bashrc. this is read every time bash starts and is where interactive things - eg PS1 should go. therefore it should be stressed that PS1=..blah.. should be in .bashrc and not .profile. </verb></tscreen> --> <tscreen><verb> PS1 文字列は .bashrc で設定すべきです。非対話型 bash は PS1 の設定をクリアして しまうからです。bash manページには、bashが対話型セッションにあるか、非 対話型(つまりスクリプト)セッションにあるかを知るよい方法がPS1が定義され ているかどうかだと書いてあります。 これを私が理解したのはstartxがbashスクリプトで、startxはあなたのプロン プトを消してしまいます。.profile(もしくは.bash_profile)でPS1を設定し、 コンソールでログインして、startxでXを起動すると、あなたのPS1は破壊され てしまい、デフォルトのプロンプトに戻ります。 解決法の一つは、xtermやrxvtを-lsオプション付きで起動し、.profileファイ ルを読み込むようにすることです。しかし、非対話型のシェルスクリプトによ ってシェルが呼ばれる度にPS1が失われます。system(3)は sh -c を使いますが、 sh が bash なら PS1 が失われます。よりよい解決法は、PS1 の定義を .bashrc に 置くことです。これは bash が起動される度に読み込まれますので、PS1 のような 対話に必要なものを置くべき場所です。 したがって、「PS1=何たらかんたら」は、.profile ではなく、.bashrc に置か れるべきです。 </verb></tscreen> <p> <!-- I tried to duplicate the problem he explains, and encountered a different one: my PROMPT_COMMAND variable (which will be introduced later) was blown away. My knowledge in this area is somewhat shaky, so I'm going to go with what Johan says. --> 私は彼の説明を再現しようとして別の問題にぶちあたりました。私の PROMPT_COMMAND 変数(次に説明します)がなくなってしまうのです。この分野での私の知識は十分で ないので、Johan が言うようにしましょう。 <sect><!--External Commands-->外部コマンド <sect1>PROMPT_COMMAND <p> <!-- Bash provides another environment variable called <bf>PROMPT_COMMAND</bf>. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt. --> Bash には、<bf>PROMPT_COMMAND</bf> という環境変数があります。この内容は Bash がプロンプトを出す前に普通の Bash のコマンドとして実行されます。 <verb> [21:55:01][giles@nikola:~] PS1="[\u@\h:\w]\$ " [giles@nikola:~] PROMPT_COMMAND="date +%H%M" 2155 [giles@nikola:~] d bin mail 2156 [giles@nikola:~] </verb> <p> <!-- What happened above was that I changed PS1 to no longer include the <TT>\t</TT> escape sequence, so the time was no longer a part of the prompt. Then I used <TT>date +%H%M</TT> to display the time in a format I like better. But it appears on a different line than the prompt. Tidying this up using <TT>echo -n ...</TT> as shown below works with Bash 2.0+, but appears not to work with Bash 1.14.7: apparently the prompt is drawn in a different way, and the following method results in overlapping text. --> ここでは、<TT>\t</TT>エスケープシーケンスは PS1 の中にはありませんので、 プロンプトには時間情報が含まれません。<TT>date +%H%M</TT>によって 私の好みのフォーマットで時間が表示されます。しかし、時間がプロンプトと 別の行に表れます。Bash 2.0+ では、<TT>echo -n ...</TT>を使ってこれを 直すことができますが、Bash 1.14.7 ではできないようです。プロンプトの 表示方法が異なっており、テキストが2回表示されるようになってしまいます。 <verb> 2156 [giles@nikola:~] PROMPT_COMMAND="echo -n [$(date +%H%M)]" [2156][giles@nikola:~]$ [2156][giles@nikola:~]$ d bin mail [2157][giles@nikola:~]$ unset PROMPT_COMMAND [giles@nikola:~] </verb> <p> <!-- <TT>echo -n ...</TT> controls the output of the date command and supress the trailing newline, allowing the prompt to appear all on one line. At the end, I used the <TT>unset</TT> command to remove the PROMPT_COMMAND environment variable. --> <TT>echo -n ...</TT>は date コマンドの出力を制御し、最後の改行を抑制する ことによって、プロンプトが1行で表示されるようになります。最後に <TT>unset</TT>コマンドを使って、環境変数 PROMPT_COMMAND を除きます。 <p> <!-- Note that I use the $(<command>) convention for command substitution: that is, --> コマンド展開を行なうのに、$(<command>)という書き方を使って いることに注意してください。つまり、 <verb> $(date +%H%M) </verb> <p> <!-- means "substitute the output from the <bf>date +%H%M</bf> command here." This works in Bash 2.0+. In some older versions of Bash, prior to 1.14.7, you may need to use backquotes (<TT>`date +%H%M`</TT>). Backquotes can be used in Bash 2.0+, but are being phased out in favor of $(), which nests better. I will continue to use this convention throughout this document. If you're using an earlier version of Bash, you can usually substitute backquotes where you see $(). If the command substitution is escaped (ie. \$(command) ), then use backslashes to escape BOTH your backquotes (ie. \'command\' ). --> は、「<bf>date +%H%M</bf>のコマンドの出力で置換する」という意味です。 これは、Bash 2.0+ では動きますが、1.14.7 以前の Bash では、バッククォート を使って、<TT>`date +%H%M`</TT>とします。Bash 2.0+ でもバッククォートは 使えますが、$()の方がネストしやすいので使われなくなっています。 この文書ではこの書き方を使っていきます。もしあなたの使っている Bash が 古いバージョンなら、$()の代わりにバッククォートを使ってください。 コマンド展開がエスケープされている時(つまり \$(command) )は、バッククォートを 両方エスケープ(つまり \`command\` )してください <sect1><!--External Commands in the Prompt-->プロンプトの中での外部コマンド <p> <!-- You can use the output of regular Linux commands directly in the prompt as well. Obviously, you don't want to insert a lot of material, or it will create a large prompt. You also want to use a <bf>fast</bf> command, because it's going to be executed every time your prompt appears on the screen, and delays in the appearance of your prompt while you're working can be very annoying. (Unlike the previous example that this closely resembles, this does work with Bash 1.14.7.) --> 普通の Linux のコマンドの出力を直接プロンプトに埋め込むこともできます。 たくさんのものを埋め込もうとはしないでください。 プロンプトが長くなりすぎます。あなたは <bf>速い</bf>コマンドを使いたいとも思っているでしょう。プロンプトが画面に 表示されるたびに実行されて、作業中にプロンプトの表示に時間がかかると イライラしますから。(前の 例に似ていますが、これは Bash 1.14.7 でも動作します。) <tscreen><verb> [21:58:33][giles@nikola:~]$ PS1="[\$(date +%H%M)][\u@\h:\w]\$ " [2159][giles@nikola:~]$ ls bin mail [2200][giles@nikola:~]$ </verb></tscreen> <p> <!-- It's important to notice the backslash before the dollar sign of the command substitution. Without it, the external command is executed exactly once: when the PS1 string is read into the environment. For this prompt, that would mean that it would display the same time no matter how long the prompt was used. The backslash protects the contents of $() from immediate shell interpretation, so "date" is called every time a prompt is generated. --> コマンド展開のドル印の前にあるバックスラッシュに注意して下さい。これが ないと外部コマンドは、PS1 文字列が環境に読み込まれる時にたった一度だけしか 実行されません。このプロンプトの場合には、どんなに長くプロンプトが 使われても、いつも同じ時間を表示することになります。 バックスラッシュを置くことによって、$()の内容がすぐには実行されなく なり、"date" はプロンプトが生成される度に実行されることになります。 <p> <!-- Linux comes with a lot of small utility programs like <bf>date</bf>, <bf>grep</bf>, or <bf>wc</bf> that allow you to manipulate data. If you find yourself trying to create complex combinations of these programs within a prompt, it may be easier to make a shell script of your own, and call it from the prompt. Escape sequences are often required in bash shell scripts to ensure that shell variables are expanded at the correct time (as seen above with the date command): this is raised to another level within the prompt PS1 line, and avoiding it by creating shell scripts is a good idea. --> Linux には多くの小さなユーティリティがついてきます。<bf>date</bf>、 <bf>grep</bf>、 <bf>wc</bf>などでデータを操作できます。このような プログラムを使って複雑なプロンプトを作るには、シェルスクリプトを 作って、それをプロンプトから実行させた方がいいでしょう。スクリプトの 中でもコマンドが正しい時に実行されるよう、エスケープシーケンスが 必要になることがあります(上のdateコマンドの例のように)。PS1の行の 中ではレベルが一段上がることになりますので、シェルスクリプトを作る ことによりこれを避けるのはよい考えです。 <p> <!-- An example of a small shell script used within a prompt is given below: --> 小さなシェルスクリプトをプロンプトの中で使う例を示しましょう。 <code> #!/bin/bash # lsbytesum - sum the number of bytes in a directory listing TotalBytes=0 for Bytes in $(ls -l | grep "^-" | cut -c30-41) do let TotalBytes=$TotalBytes+$Bytes done TotalMeg=$(echo -e "scale=3 \n$TotalBytes/1048576 \nquit" | bc) echo -n "$TotalMeg" </code> <!-- Combo Verified! 8 Oct 98 --> <p> <!-- I have at times kept this both as a function (much more efficient - unfortunately, explaining functions in detail is beyond the scope of this document), or as a shell script in my ~/bin directory, which is on my path. Used in a prompt: --> このようなものを関数(の方が効率的ですが、この文書では関数の書き方は 残念ながら扱いません)にしたり、パスの通っている ~/bin ディレクトリの中に シェルスクリプトとして保存しておきます。プロンプトの中での使い方は、 <tscreen><verb> [2158][giles@nikola:~]$ PS1="[\u@\h:\w (\$(lsbytesum) Mb)]\$ " [giles@nikola:~ (0 Mb)]$ cd /bin [giles@nikola:/bin (4.498 Mb)]$ </verb></tscreen> <sect1><!--What to Put in Your Prompt-->プロンプトに何を置くか <p> <!-- You'll find I put username, machine name, time, and current directory name in most of my prompts. With the exception of the time, these are very standard items to find in a prompt, and time is probably the next most common addition. But what you include is entirely a matter of personal taste. Here are examples from people I know to help give you ideas. --> 私が示すプロンプトの例では、ほとんどいつもユーザー名、機械名、時間、現在の ディレクトリ名が表示されることにお気づきでしょう。時間を除けば、これらは プロンプトに表示される標準のもので、時間はおそらくその次に追加されることの 多いものでしょう。でも何をいれるかは、全く個人の趣味にかかるものです。 ここでは、私の知っている人たちの例を示してあなたに参考にしてもらいましょう。 <p> <!-- Dan's prompt is minimal but very effective, particularly for the way he works. --> Danのプロンプトは短いけれども効果的です。特に彼の仕事のやり方にとって。 <verb> [giles@nikola:~]$ cur_tty=$(tty | sed -e "s/.*tty\(.*\)/\1/") [giles@nikola:~]$ echo $cur_tty p4 [giles@nikola:~]$ PS1="\!,$cur_tty,\$?\$ " 1095,p4,0$ </verb> <p> <!-- Dan doesn't like that having the current working directory can resize the prompt drastically as you move through the directory tree, so he keeps track of that in his head (or types "pwd"). He learned Unix with csh and tcsh, so he uses his command history extensively (something many of us weened on Bash do not do), so the first item in the prompt is the history number. The second item is the significant characters of the tty, (the output of "tty" is cropped with sed), an item that can be useful to "screen" users. The third item is the exit value of the last command/pipeline (note that this is rendered useless by any command executed within the prompt - you could work around that by capturing it to a variable and playing it back, though). Finally, the "\$" is a dollar sign for a regular user, and switches to a hash mark ("#") if the user is root. --> Danは、ディレクトリツリーを動き回っている間、プロンプトの長さが急に大幅に 変わるので、現在のディレクトリを表示するのは好きではありません。だからそれは 頭にたたき込んでおきます(またはpwdコマンドを使います)。彼は Unix を csh や tcsh で学んだので、コマンドヒストリーを よく使います(Bash 使いはあまりそうはしないようです)ので、プロンプトの最初に ヒストリ番号を表示します。次に(tty コマンドの出力を sed で加工して)tty の 文字列の中の特徴的な部分を表示します。これは "screen" を使っている人の 役に立ちます。三番目に、最後に使ったコマンドや パイプラインの exit 値を表示します(これはプロンプトから実行されるコマンド では意味がありませんので、exit値を別の変数に捕えて表示するようなことを 考える必要があります)。最後に \$ で通常のユーザーでは $ を、root に対しては # を表示するようにします。 <p> <!-- Torben Fjerdingstad wrote to tell me that he often suspends jobs, and then forgets about them, so he uses his prompt to remind him of suspended jobs: --> Torben Fjerdingstad は、時々ジョブをサスペンドし、そのことについて忘れて しまうので、サスペンド中のジョブを思い出させてくれるプロンプトを使っている とメールしてくれました。 <tscreen><verb> [giles@nikola:~]$ function jobcount { > jobs|wc -l| awk '{print $1}' > } [giles@nikola:~]$ export PS1='\W[`jobcount`]# ' giles[0]# man ls & [1] 4150 [1]+ Stopped (tty output) man ls giles[1]# </verb></tscreen> <p> <!-- Torben uses <bf>awk</bf> to trim the whitespace from the output of wc, while I would have used sed or tr - not because they're better, but because I'm more familiar with them. There are probably other ways as well. Torben also surrounds his PS1 string in single quotes, which prevent Bash from immediately interpreting the backquotes, so he doesn't have to escape them as I have mentioned. --> Torben は、<bf>awk</bf>で wc の出力の中のスペースを削っています。私なら sed か tr を使うことでしょう。その方がいいからではなく、その方が慣れて いるからです。他の方法もあることでしょう。Torben は PS1 文字列をシングル クォートで囲んでいますが、これは Bash がバッククォートを直ちに解釈するのを 防ぎます。私が述べたエスケープの方法は使っていません。 <p> <!-- <bf>NOTE:</bf> There is a known bug in Bash 2.02 that causes the <bf>jobs</bf> command (a shell builtin) to return nothing to a pipe. If you try the above under Bash 2.02, you will always get a "0" back regardless of how many jobs you have suspended. Chet Ramey, one of the maintainers of Bash, tells me that this will be fixed for v2.03. --> <bf>注意:</bf> Bash 2.02 にはシェルの組み込みコマンドである <bf>jobs</bf> が パイプに何も渡さないというバグが知られています。上のコードを Bash 2.02 で 試すと、サスペンドしたジョブがいくつあっても0が帰ってきます。Bash の保守を している一人である Chet Ramey は、v2.03 ではこれを直すと言っています。 <sect1><!--Bash Environment and Functions-->Bash の環境と関数 <p> <!-- As mentioned earlier, PS1, PS2, PS3, PS4, and PROMPT_COMMAND are all stored in the Bash environment. For those of us coming from a DOS background, the idea of tossing big hunks of code into the environment is horrifying, because that DOS environment was small, and didn't exactly grow well. There are probably practical limits on what you can and should put in the environment, but I don't know what they are, and we're probably talking a couple of orders of magnitude larger than what DOS users are used to. As my Dan put it: --> すでに述べたように、PS1、PS2、PS3、PS4、PROMPT_COMMAND はすべて Bash の環境に保存されます。私たちのように DOS からきたものにとって、 DOS の環境領域は狭く、うまく拡張できなかったので、環境に多くの文字を いれるのは恐怖です。おそらく環境の大きさには実際上の上限があるので しょうが、私は知りませんし、DOS ユーザーが慣れていた大きさの何倍もの オーダーの話なのでしょう。Dan は次のように言っています。 <p> <!-- "In my interactive shell I have 62 aliases and 25 functions. My rule of thumb is that if I need something solely for interactive use and can handily write it in bash I make it a shell function (assuming it can't be easily expressed as an alias). If these people are worried about memory they don't need to be using bash. Bash is one of the largest programs I run on my linux box (outside of Oracle). Run top sometime and press 'M' to sort by memory - see how close bash is to the top of the list. Heck, it's bigger than sendmail! Tell 'em to go get ash or something." --> 「私の使っている対話型のシェルには、エイリアスが62と関数が25ある。 対話型だけで使うもので、簡単に bash で書ける場合は、関数にしている (エイリアスで書くには難しい場合)。もしメモリが気になるなら、bash を 使わない方がいいだろう。bash は私の linux box で動いているプログラムの 中で Oracle の次に大きい。top コマンドを時々動かして、M を押してメモリの 大きさでソートしてごらん。bash がほとんど一番上に近いところにあるのが わかるだろう。sendmail より大きいんだよ! メモリが気になるなら ash のような ものを使えばいい。」 <p> <!-- I guess he was using console only the day he tried that: running X and X apps, I have a lot of stuff larger than Bash. But the idea is the same: the environment is something to be used, and don't worry about overfilling it. --> こう書いた時彼はコンソールだけを使っていたのでしょう。X や X アプリケーション を動かせば、Bash より大きいのがいっぱいあります。でも考え方は同じです。 環境は使うべきもので、使い過ぎを心配する必要はないのですから。 <p> <!-- I risk censure by Unix gurus when I say this (for the crime of over-simplification), but functions are basically small shell scripts that are loaded into the environment for the purpose of efficiency. Quoting Dan again: "Shell functions are about as efficient as they can be. It is the approximate equivalent of sourcing a bash/bourne shell script save that no file I/O need be done as the function is already in memory. The shell functions are typically loaded from [.bashrc or .bash_profile] depending on whether you want them only in the initial shell or in subshells as well. Contrast this with running a shell script: Your shell forks, the child does an exec, potentially the path is searched, the kernel opens the file and examines enough bytes to determine how to run the file, in the case of a shell script a shell must be started with the name of the script as its argument, the shell then opens the file, reads it and executes the statements. Compared to a shell function, everything other than executing the statments can be considered unnecessary overhead." --> こう書くと、Unix の導師たちには単純化しすぎていると検閲を受けるかもしれません。 しかし関数は基本的に小さなシェルスクリプトで、効率のために環境に読み込まれて います。Dan の言葉を借りれば「シェル関数は、限界に近いところまで効率的だ。 シェルスクリプトを source するのとほぼ同様のことをファイル入出力なしに 実行できる。すでにメモリに読み込まれているからだ。シェル関数は通常 ログインシェルかサブシェルかによって、.bashrc か .bash_profile ファイルから 読み込まれる。シェルスクリプトを動かす場合には、現在のシェルは fork し、 子プロセスが exec を行ない、おそらくパスが探され、カーネルはファイルを 開き、実行するのに十分なメモリがあるか確かめ、シェルスクリプトであった 場合には新しいシェルをスクリプト名を引数として与えて起動し、そのシェル がファイルを開いて、各行を実行する。シェル関数の場合と比べると、各行を 実行する以外の部分は不必要なオーバーヘッドにすぎない。」 <sect><!--Xterm Title Bar Manipulations-->Xtermのタイトルバーの操作 <p> <!-- Non-printing escape sequences can be used to produce interesting effects in prompts. To use these escape sequences, you need to enclose them in <bf>\[</bf> and <bf>\]</bf>, telling Bash to ignore this material while calculating the size of the prompt. Failing to include these delimiters results in line editing code placing the cursor in the wrong place because it doesn't know the actual size of the prompt. Escape sequences must also be preceded by <bf>\033[</bf> in Bash prior to version 2, or by either <bf>\033[</bf> or <bf>\e[</bf> in later versions. --> 表示されないエスケープシーケンスはプロンプトに興味深い効果をもたらすために 用いられます。このようなエスケープシーケンスを用いるには、<bf>\[</bf> と <bf>\]</bf> で囲んでやり、Bashがプロンプトの大きさを計算する時に無視させ ます。この区切りを入れてやらないと、行編集の際のカーソルの位置の計算が 違ってきます。エスケープシーケンスは、バージョン2より以前の Bash では <bf>\033[</bf> からはじめ、それ以降のバージョンでは、<bf>\033[</bf> でも <bf>\e[</bf> でもはじめることができます。 <p> <!-- If you try to change the title bar of your Xterm with your prompt when you're at the console, you'll produce garbage in your prompt. To avoid this, test the TERM environment variable to tell if your prompt is going to be in an Xterm. --> コンソールを使っている時に Xterm のタイトルバーを変えようとすると、 プロンプトにごみが入ります。これを避けるには環境変数 TERM を調べて、 Xterm の時だけそのプロンプトを使うようにします。 <code> function proml { case $TERM in xterm*) local TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) local TITLEBAR='' ;; esac PS1="${TITLEBAR}\ [\$(date +%H%M)]\ [\u@\h:\w]\ \$ " PS2='> ' PS4='+ ' } </code> <p> <!-- This is a function that can be incorporated into ~/.bashrc. The function name could then be called to execute the function. The function, like the PS1 string, is stored in the environment. Once the PS1 string is set by the function, you can remove the function from the environment with <TT>unset proml</TT>. Since the prompt can't change from being in an Xterm to being at the console, the TERM variable isn't tested every time the prompt is generated. I used continuation markers (backslashes) in the definition of the prompt, to allow it to be continued on multiple lines. This improves readability, making it easier to modify and debug. --> これは、~/.bashrc に書いておく関数です。この関数名を呼ぶと実行されます。 関数は、PS1 文字列と同様環境に置かれます。PS1 変数がこの関数で定義され たら、この関数を<TT>unset proml</TT>で環境から取り除くことができます。 Xterm にいる間はコンソールに変わることがありませんから、変数TERMを プロンプトを出す度にチェックする必要はありません。継続行のしるし (バックスラッシュ)をプロンプトの定義の中で使っているのは、複数行に またがるようにして、読み易さを増し、修正したり、デバッグするのを 容易にしています。 <p> <!-- I define this as a function because this is how the Bashprompt package (discussed later in this document) deals with prompts: it's not the only way to do it, but it works well. As the prompts you use become more complex, it becomes more and more cumbersome to type them in at the prompt, and more practical to make them into some sort of text file. In this case, to test this at the prompt, save the above as a text file called "proml". You can work with it as follows: --> これを関数にしてあるのは、後で説明する Bashprompt パッケージのやり方です。 こうしなければならないということではありませんが、このやり方はうまく いきます。あなたの使うプロンプトが複雑になってくればくるほど、それを プロンプトのところでタイプするのは面倒になり、テキストファイルで保存 する必要が生じてきます。今回は上の関数を proml というテキストファイルに 保存しましょう。次のようにします。 <tscreen><verb> [giles@nikola:/bin (4.498 Mb)]$ cd -> プロンプトを保存したいディレクトリに移動 [giles@nikola:~ (0 Mb)]$ vi proml -> プロンプトファイルを編集 ... -> 上のテキストを入力 [giles@nikola:~ (0 Mb)]$ source proml -> プロンプト関数の読み込み [giles@nikola:~ (0 Mb)]$ proml -> プロンプト関数の実行 </verb></tscreen> <p> <!-- The first step in creating this prompt is to test if the shell we're starting is an xterm or not: if it is, the shell variable (${TITLEBAR}) is defined. It consists of the appropriate escape sequences, and <bf>\u@\h:\w</bf>, which puts <user>@<machine>:<working directory> in the Xterm title bar. This is particularily useful with minimized Xterms, making them more rapidly identifiable. The other material in this prompt should be familiar from previous prompts we've created. --> このプロンプトを作成する第一段階は、シェルが xterm かどうかをチェックする ことです。もしxtermなら、シェル変数(${TITLEBAR})が定義されます。 その内容は適切なエスケープシーケンスと<bf>\u@\h:\w</bf>で、その結果、 <ユーザー名>@<マシン名>:<ディレクトリ>が Xterm の タイトルバーに表示されます。これは特に Xterm を最小化した時に同定しやすく してくれます。このプロンプトのそれ以外の部分はすでに今まで作ったプロンプト でおなじみのものです。 <p> <!-- The only drawback to manipulating the Xterm title bar like this occurs when you log into a system on which you haven't set up the title bar hack: the Xterm will continue to show the information from the previous system that had the title bar hack in place. --> このように Xterm のタイトルバーを操作する唯一のデメリットは、このような タイトルバーになるようにセットしていない機械を使ったとき、タイトルバー が元のままになってしまうことです。 <sect><!--ANSI Escape Sequences: Colours and Cursor Movement-->ANSI エスケープシーケンス: 色とカーソル操作 <sect1><!--Colours-->色 <p> <!-- As mentioned before, non-printing escape sequences have to be enclosed in <bf>\[\033[</bf> and <bf>\]</bf>. For colour escape sequences, they should also be followed by a lowercase <bf>m</bf>. --> すでに述べたように表示されないエスケープシーケンスは、<bf>\[\033[</bf> と <bf>\]</bf> で囲んでやる必要があります。色のエスケープシーケンスの場合は 後ろに <bf>m\]</bf> をつけてやる必要があります。 <p> <!-- If you try out the following prompts in an xterm and find that you aren't seeing the colours named, check out your ~/.Xdefaults file (and possibly its bretheren) for lines like "XTerm*Foreground: BlanchedAlmond". This can be commented out by placing an exclamation mark ("!") in front of it. Of course, this will also be dependent on what terminal emulator you're using. This is the likeliest place that your term foreground colours would be overridden. --> もしこれから説明するプロンプトを試してみて、指定した色がうまく表示され ないなら、~/.Xdefaults ファイル(あるいはそれと同等のファイル)に "XTerm*Foreground: BlanchedAlmond" のような行がないか調べてください。 この前に!マークをつけることによって、コメントアウトすることができます。 これは、あなたがどのような端末エミュレータを使っているかにも依存します。 あなたの端末の色が上書きされる可能性のもっとも高いのがこのファイルです。 <p> <!-- To include blue text in the prompt: --> プロンプトにブルーのテキストを入れるには、 <tscreen><verb> PS1="\[\033[34m\][\$(date +%H%M)][\u@\h:\w]$ " </verb></tscreen> <!-- The problem with this prompt is that the blue colour that starts with the 34 colour code is never switched back to the regular colour, so any text you type after the prompt is still in the colour of the prompt. This is also a dark shade of blue, so combining it with the <bf>bold</bf> code might help: --> このプロンプトの問題は、34のカラーコードで変えたブルーの色がもとの色に戻らない ので、プロンプトの後にタイプした文字もプロンプトと同じ色になってしまう ことです。また、このブルーは暗いので、<bf>bold</bf> コードも組み合わせます。 <tscreen><verb> PS1="\[\033[1;34m\][\$(date +%H%M)][\u@\h:\w]$\[\033[0m\] " </verb></tscreen> <p> <!-- The prompt is now in light blue, and it ends by switching the colour back to nothing (whatever foreground colour you had previously). --> プロンプトは明るいブルーに変わり、最後に色をなしにしています。(色なしは、 元のフォアグラウンドカラーです。) <p> <!-- Here are the rest of the colour equivalences: --> 色は次のように定義されています。 <tscreen><verb> Black 0;30 Dark Gray 1;30 Blue 0;34 Light Blue 1;34 Green 0;32 Light Green 1;32 Cyan 0;36 Light Cyan 1;36 Red 0;31 Light Red 1;31 Purple 0;35 Light Purple 1;35 Brown 0;33 Yellow 1;33 Light Gray 0;37 White 1;37 </verb></tscreen> <p> <!-- You can also set background colours by using 44 for Blue background, 41 for a Red background, etc. There are no bold background colours. Combinations can be used, like Light Red text on a Blue background: <bf>\[\033[44;1;31m\]</bf>, although setting the colours separately seems to work better (ie. <bf>\[\033[44m\]\[\033[1;31m\]</bf>). Other codes available include 4: Underscore, 5: Blink, 7: Inverse, and 8: Concealed. --> バックグラウンドカラーもこの方法で指定することができます。たとえば44なら ブルー、41なら赤というふうになっています。 バックグラウンドカラーにはボールドのものがありません。 ブルーの背景にライトレッドのテキストを表示するなら、 <bf>\[\033[44;1;31m\]</bf> のように組み合わせて使うこともできまが、 <bf>\[\033[44m\]\[\033[1;31m\]</bf> のように分けて設定した方がいいようです。 他のコードとしては、4:下線、5:点滅、7:逆転、8:非表示などがあります。 <p> <!-- <bf>Aside:</bf> Many people (myself included) object strongly to the "blink" attribute. Fortunately, it doesn't work in any terminal emulators that I'm aware of - but it will still work on the console. And, if you were wondering (as I did) "What use is a 'Concealed' attribute?!" - I saw it used in an example shell script (not a prompt) to allow someone to type in a password without it being echoed to the screen. --> <bf>注:</bf>多くの人(私を含め)は、点滅属性に強く反対します。幸いこれは 端末エミュレータでは作動しませんが、コンソールでは機能します。また、 (私がそうであるように)非表示属性は何のためにあるのだろうと思うでしょう。 (プロンプトではなく)シェルスクリプトの例で、パスワードを入力してもスクリーン に表示されないように使われているのを見たことがあります。 <p> <!-- Based on a prompt called "elite2" in the Bashprompt package (which I have modified to work better on a standard console, rather than with the special xterm fonts required to view the original properly), this is a prompt I've used a lot: --> Bashprompt パッケージの中の elite2 というプロンプトを(元のが xterm のフォント で用いるようになっていたので、コンソールで使えるように)修正したものは、 私のよく使っていたものです。 <code> function elite { local GRAY="\[\033[1;30m\]" local LIGHT_GRAY="\[\033[0;37m\]" local CYAN="\[\033[0;36m\]" local LIGHT_CYAN="\[\033[1;36m\]" case $TERM in xterm*) local TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) local TITLEBAR="" ;; esac local GRAD1=$(tty|cut -d/ -f3) PS1="$TITLEBAR\ $GRAY-$CYAN-$LIGHT_CYAN(\ $CYAN\u$GRAY@$CYAN\h\ $LIGHT_CYAN)$CYAN-$LIGHT_CYAN(\ $CYAN\#$GRAY/$CYAN$GRAD1\ $LIGHT_CYAN)$CYAN-$LIGHT_CYAN(\ $CYAN\$(date +%H%M)$GRAY/$CYAN\$(date +%d-%b-%y)\ $LIGHT_CYAN)$CYAN-$GRAY-\ $LIGHT_GRAY\n\ $GRAY-$CYAN-$LIGHT_CYAN(\ $CYAN\$$GRAY:$CYAN\w\ $LIGHT_CYAN)$CYAN-$GRAY-$LIGHT_GRAY " PS2="$LIGHT_CYAN-$CYAN-$GRAY-$LIGHT_GRAY " } </code> <p> <!-- I define the colours as temporary shell variables in the name of readability. It's easier to work with. The "GRAD1" variable is a check to determine what terminal you're on. Like the test to determine if you're working in an Xterm, it only needs to be done once. The prompt you see look like this, except in colour: --> 色を一時的シェル変数として読み易いものに定義します。GRAD1 変数は 使っている端末を決めるのに用いています。Xterm 上かどうかのチェックと 同様、これも一度行なえば十分です。結果は色を除けばこのように見えます。 <tscreen><verb> --(giles@nikola)-(75/ttyp7)-(1908/12-Oct-98)-- --($:~/tmp)-- </verb></tscreen> <p> <!-- To help myself remember what colours are available, I wrote the following script which echoes all the colours to screen: --> どんな色が使えるのかを思い出すために、次のスクリプトはすべての色をスクリーン にエコーします。 <!-- <code> #!/bin/bash # # This file echoes a bunch of colour codes to the terminal to demonstrate # what's available. Each line is one colour on black and gray # backgrounds, with the code in the middle. Verified to work on white, # black, and green BGs (2 Dec 98). # echo " On Light Gray: On Black:" echo -e "\033[47m\033[1;37m White \033[0m\ 1;37m \ \033[40m\033[1;37m White \033[0m" echo -e "\033[47m\033[37m Light Gray \033[0m\ 37m \ \033[40m\033[37m Light Gray \033[0m" echo -e "\033[47m\033[1;30m Gray \033[0m\ 1;30m \ \033[40m\033[1;30m Gray \033[0m" echo -e "\033[47m\033[30m Black \033[0m\ 30m \ \033[40m\033[30m Black \033[0m" echo -e "\033[47m\033[31m Red \033[0m\ 31m \ \033[40m\033[31m Red \033[0m" echo -e "\033[47m\033[1;31m Light Red \033[0m\ 1;31m \ \033[40m\033[1;31m Light Red \033[0m" echo -e "\033[47m\033[32m Green \033[0m\ 32m \ \033[40m\033[32m Green \033[0m" echo -e "\033[47m\033[1;32m Light Green \033[0m\ 1;32m \ \033[40m\033[1;32m Light Green \033[0m" echo -e "\033[47m\033[33m Brown \033[0m\ 33m \ \033[40m\033[33m Brown \033[0m" echo -e "\033[47m\033[1;33m Yellow \033[0m\ 1;33m \ \033[40m\033[1;33m Yellow \033[0m" echo -e "\033[47m\033[34m Blue \033[0m\ 34m \ \033[40m\033[34m Blue \033[0m" echo -e "\033[47m\033[1;34m Light Blue \033[0m\ 1;34m \ \033[40m\033[1;34m Light Blue \033[0m" echo -e "\033[47m\033[35m Purple \033[0m\ 35m \ \033[40m\033[35m Purple \033[0m" echo -e "\033[47m\033[1;35m Pink \033[0m\ 1;35m \ \033[40m\033[1;35m Pink \033[0m" echo -e "\033[47m\033[36m Cyan \033[0m\ 36m \ \033[40m\033[36m Cyan \033[0m" echo -e "\033[47m\033[1;36m Light Cyan \033[0m\ 1;36m \ \033[40m\033[1;36m Light Cyan \033[0m" </code> --> <code> #!/bin/bash # # このファイルは、様々なカラーコードを端末にエコーし、どんな色が # 使用可能かを示します。 # それぞれの行では、黒とグレイの背景の上に一つの色を示し、コードを中央に # 表示しています。白、黒、グリーンの背景色で確認してあります。(2 Dec 98) # echo " On Light Gray: On Black:" echo -e "\033[47m\033[1;37m White \033[0m\ 1;37m \ \033[40m\033[1;37m White \033[0m" echo -e "\033[47m\033[37m Light Gray \033[0m\ 37m \ \033[40m\033[37m Light Gray \033[0m" echo -e "\033[47m\033[1;30m Gray \033[0m\ 1;30m \ \033[40m\033[1;30m Gray \033[0m" echo -e "\033[47m\033[30m Black \033[0m\ 30m \ \033[40m\033[30m Black \033[0m" echo -e "\033[47m\033[31m Red \033[0m\ 31m \ \033[40m\033[31m Red \033[0m" echo -e "\033[47m\033[1;31m Light Red \033[0m\ 1;31m \ \033[40m\033[1;31m Light Red \033[0m" echo -e "\033[47m\033[32m Green \033[0m\ 32m \ \033[40m\033[32m Green \033[0m" echo -e "\033[47m\033[1;32m Light Green \033[0m\ 1;32m \ \033[40m\033[1;32m Light Green \033[0m" echo -e "\033[47m\033[33m Brown \033[0m\ 33m \ \033[40m\033[33m Brown \033[0m" echo -e "\033[47m\033[1;33m Yellow \033[0m\ 1;33m \ \033[40m\033[1;33m Yellow \033[0m" echo -e "\033[47m\033[34m Blue \033[0m\ 34m \ \033[40m\033[34m Blue \033[0m" echo -e "\033[47m\033[1;34m Light Blue \033[0m\ 1;34m \ \033[40m\033[1;34m Light Blue \033[0m" echo -e "\033[47m\033[35m Purple \033[0m\ 35m \ \033[40m\033[35m Purple \033[0m" echo -e "\033[47m\033[1;35m Pink \033[0m\ 1;35m \ \033[40m\033[1;35m Pink \033[0m" echo -e "\033[47m\033[36m Cyan \033[0m\ 36m \ \033[40m\033[36m Cyan \033[0m" echo -e "\033[47m\033[1;36m Light Cyan \033[0m\ 1;36m \ \033[40m\033[1;36m Light Cyan \033[0m" </code> <sect1><!--Cursor Movement-->カーソル操作 <p> <!-- ANSI escape sequences allow you to move the cursor around the screen at will. This is more useful for full screen user interfaces generated by shell scripts, but can also be used in prompts. The movement escape sequences are as follows: --> ANSIエスケープシーケンスでカーソルをスクリーン上で自由に動かせます。 これはシェルスクリプトでフルスクリーンのユーザーインターフェースを 作る時に役に立ちますが、プロンプトでも使えます。カーソル操作エスケープ シーケンスは次のとおりです。 <!-- <tscreen><verb> - Position the Cursor: \033[<L>;<C>H puts the cursor at line L and column C. - Move the cursor up N lines: \033[<N>A - Move the cursor down N lines: \033[<N>B - Move the cursor forward N columns: \033[<N>C - Move the cursor backward N columns: \033[<N>D - Save cursor position: \033[s - Restore cursor position: \033[u </verb></tscreen> --> <tscreen><verb> - カーソルの位置を決める。 \033[<L>;<C>H カーソルを L 行 C 列に置きます。 - カーソルを N 行上に動かす。 \033[<N>A - カーソルを N 行下に動かす。 \033[<N>B - カーソルを C 列右に動かす。 \033[<>C - カーソルを C 列左に動かす。 \033[<C>D - カーソルの位置を記憶する。 \033[s - 記憶していたカーソルの位置に戻す。 \033[u </verb></tscreen> <p> <!-- The latter two codes are NOT honoured by many terminal emulators. The only ones that I'm aware of that do are xterm and nxterm - even though the majority of terminal emulators are based on xterm code. As far as I can tell, rxvt, kvt, xiterm, and Eterm do not support this. They are supported on the console. --> 最後の二つのコードは多くの端末エミュレータで実現されていません。私の知って いる限りでは、xterm と nxterm では実現されています。多くの端末エミュレータが xterm のコードに基づいているにもかかわらず。私が確認した限り、rxvt、kvt、 xiterm、Eterm はサポートしていません。コンソールではサポートされています。 <p> <!-- Try putting in the following line of code at the prompt (it's a little clearer what it does if the prompt is several lines down the terminal when you put this in): <tt>echo -en "\033[7A\033[1;35m BASH \033[7B\033[6D"</tt> This should move the cursor seven lines up screen, print the word " BASH ", and then return to where it started to produce a normal prompt. This isn't a prompt: it's just a demonstration of moving the cursor on screen, using colour to emphasize what has been done. --> 次のコードをプロンプトにいれてみて下さい。(これが何をしているのかをはっきり させるには、端末の上から何行か下でこれを実行して下さい。) <tt>echo -en "\033[7A\033[1;35m BASH \033[7B\033[6D"</tt> これは、カーソルを7行上に上げて" BASH "と表示し、元のプロンプトのところに カーソルを戻します。これはプロンプトではありません。何が起こっているかを はっきりさせるために色を変えて、カーソルをスクリーン上で動かしてみせている だけです。 <p> <!-- Save this in a file called "clock": --> 次を"clock"という名前のファイルに入れて下さい。 <code> #!/bin/bash function prompt_command { let prompt_x=$COLUMNS-5 } PROMPT_COMMAND=prompt_command function clock { local BLUE="\[\033[0;34m\]" local RED="\[\033[0;31m\]" local LIGHT_RED="\[\033[1;31m\]" local WHITE="\[\033[1;37m\]" local NO_COLOUR="\[\033[0m\]" case $TERM in xterm*) TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) TITLEBAR="" ;; esac PS1="${TITLEBAR}\ \[\033[s\033[1;\$(echo -n \${prompt_x})H\]\ $BLUE[$LIGHT_RED\$(date +%H%M)$BLUE]\[\033[u\033[1A\] $BLUE[$LIGHT_RED\u@\h:\w$BLUE]\ $WHITE\$$NO_COLOUR " PS2='> ' PS4='+ ' } </code> <p> <!-- This prompt is fairly plain, except that it keeps a 24 hour clock in the upper right corner of the terminal (even if the terminal is resized). This will NOT work on the terminal emulators that I mentioned that don't accept the save and restore cursor position codes. If you try to run this prompt in any of those terminal emulators, the clock will appear correctly, but the prompt will be trapped on the second line of the terminal. --> このプロンプトで行なわれていることは比較的単純で、端末の右上に24時間制の 時刻が表示されます。(端末のサイズを変えても大丈夫です。)これは、カーソルの 位置の記憶と回復をサポートしていない端末エミュレータではうまくいきません。 そのような端末エミュレータでこれを実行すると、時刻は正確に表示されますが、 プロンプトは端末の2行目から動きません。 <p> <!-- See also <ref id="clock3" name="The Elegant Useless Clock Prompt"> for a more extensive use of these codes. --> これらのコードをもっと沢山使った例は、 <ref id="clock3" name="役立たずのエレガントな時刻表示プロンプト">にあります。 <sect1><!--Moving the Cursor With tput-->tput でカーソルを動かす <p> <!-- As with so many things in Unix, there is more than one way to achieve the same ends. A utility called "tput" can also be used to move the cursor around the screen, or get back information about the status of the terminal. "tput" for cursor positioning is less flexible than ANSI escape sequences: you can only move the cursor to an absolute position, you can't move it relative to its current position. I don't use "tput," so I'm not going to explain it in detail. Type "man tput" and you'll know as much as I do. --> Unix での多くのことがそうであるように、同じ結果を得るには、二つ以上の方法が あります。tput と呼ばれるユーティリティでもスクリーン上でカーソルを動かせ ます。tput はカーソル操作では ANSI よりも柔軟性が低く、画面上の指定した座標に 動かすことができるだけで、現在の位置から相対的に動かすことはできません。 私は"tput"を使いませんので、これ以上詳しくは説明しません。"man tput"と すれば私の知っていることが分かります。 <sect><!--Special Characters: Octal Escape Sequences-->特別な文字: 8進数エスケープシーケンス <p> <!-- Outside of the characters that you can type on your keyboard, there are a lot of other characters you can print on your screen. I've created a script to allow you to check out what the font you're using has available for you. The main command you need to use to utilise these characters is "echo -e". The "-e" switch tells echo to enable interpretation of backslash-escaped characters. What you see when you look at octal 200-400 will be very different with a VGA font from what you will see with a standard Linux font. Be warned that some of these escape sequences have odd effects on your terminal, and I haven't tried to prevent them from doing whatever they do. The linedraw and block characters (which many of us became familiar with with Word Perfect) that are used heavily by the Bashprompt project are between octal 260 and 337. --> キーボードから入力できる文字以外にも、スクリーン上に表示できる文字は沢山 あります。あなたがどんなフォントを使っているのかを確認するためのスクリプトを 作ってみましたので、使ってみて下さい。このような文字を使うために必要な 主なコマンドは"echo -e"です。"-e"スイッチにより、echo はバックスラッシュで エスケープされた文字を解釈するようになります。8進数200-400で表示されるのは、 標準の Linux フォントと VGA フォントでは非常に異なっています。これらの エスケープシーケンスがあなたの端末でおかしな結果を表示するかもしれません ので、注意して下さい。そうなることを防ぐようにはしてありません。Bashprompt でよく用いられている(Word Perfect でなじみになった)罫線や四角の文字は、 8進数260から337にあります。 <!-- <code> #!/bin/bash # Script: escgen function usage { echo -e "\033[1;34mescgen\033[0m <lower_octal_value> [<higher_octal_value>]" echo " Octal escape sequence generator: print all octal escape sequences" echo " between the lower value and the upper value. If a second value" echo " isn't supplied, print eight characters." echo " 1998 - Giles Orr, no warranty." exit 1 } if [ "$#" -eq "0" ] then echo -e "\033[1;31mPlease supply one or two values.\033[0m" usage fi let lower_val=${1} if [ "$#" -eq "1" ] then # If they don't supply a closing value, give them eight characters. upper_val=$(echo -e "obase=8 \n ibase=8 \n $lower_val+10 \n quit" | bc) else let upper_val=${2} fi if [ "$#" -gt "2" ] then echo -e "\033[1;31mPlease supply two values.\033[0m" echo usage fi if [ "${lower_val}" -gt "${upper_val}" ] then echo -e "\033[1;31m${lower_val} is larger than ${upper_val}." echo usage fi if [ "${upper_val}" -gt "777" ] then echo -e "\033[1;31mValues cannot exceed 777.\033[0m" echo usage fi let i=$lower_val let line_count=1 let limit=$upper_val while [ "$i" -lt "$limit" ] do octal_escape="\\$i" echo -en "$i:'$octal_escape' " if [ "$line_count" -gt "7" ] then echo # Put a hard return in. let line_count=0 fi let i=$(echo -e "obase=8 \n ibase=8 \n $i+1 \n quit" | bc) let line_count=$line_count+1 done echo </code> --> <code> #!/bin/bash # Script: escgen function usage { echo -e "\033[1;34mescgen\033[0m <lower_octal_value> [<higher_octal_value>]" echo " 8進数エスケープシーケンスジェネレーター:下限の値から上限の値までの" echo " すべての8進数エスケープシーケンスを表示します。もし、2番目の上限の" echo " 値が与えられなければ、8個の文字が表示されます。" echo " 1998 - Giles Orr, no warranty." exit 1 } if [ "$#" -eq "0" ] then echo -e "\033[1;31mPlease supply one or two values.\033[0m" usage fi let lower_val=${1} if [ "$#" -eq "1" ] then # もし上限値が与えられない場合は、8個にする。 upper_val=$(echo -e "obase=8 \n ibase=8 \n $lower_val+10 \n quit" | bc) else let upper_val=${2} fi if [ "$#" -gt "2" ] then echo -e "\033[1;31mPlease supply two values.\033[0m" echo usage fi if [ "${lower_val}" -gt "${upper_val}" ] then echo -e "\033[1;31m${lower_val} is larger than ${upper_val}." echo usage fi if [ "${upper_val}" -gt "777" ] then echo -e "\033[1;31mValues cannot exceed 777.\033[0m" echo usage fi let i=$lower_val let line_count=1 let limit=$upper_val while [ "$i" -lt "$limit" ] do octal_escape="\\$i" echo -en "$i:'$octal_escape' " if [ "$line_count" -gt "7" ] then echo # Put a hard return in. let line_count=0 fi let i=$(echo -e "obase=8 \n ibase=8 \n $i+1 \n quit" | bc) let line_count=$line_count+1 done echo </code> <p> <!-- You can also use <bf>xfd</bf> to display all the characters in an X font, with the command "xfd -fn <fontname>". Clicking on any given character will give you lots of information about that character, including its octal value. The script given above will be useful on the console, and if you aren't sure of the current font name. --> <bf>xfd</bf> を使って X フォントに含まれるすべての文字を表示することも できます。 コマンドは、"xfd -fn <fontname>"です。ある文字の上でクリックすると、 その8進法での値を含め、その文字に関する様々な情報が得られます。上のスクリプト は、コンソール上で現在のフォント名が分からない時に役に立つでしょう。 <sect><!--The Bash Prompt Package-->Bash Promptパッケージ <sect1><!--Availability-->入手方法 <p> <!-- The Bash Prompt package is available at <htmlurl url="http://bash.current.nu" name="http://bash.current.nu">, and is the work of several people, co-ordinated by Rob Current (aka BadLandZ). The package is an early beta, but offers a simple way of using multiple prompts (or themes), allowing you to set prompts for login shells, and for subshells (ie. putting PS1 strings in ~/.bash_profile and ~/.bashrc). Most of the themes use the extended VGA character set, so they look bad unless they're used with VGA fonts (which aren't the default on most systems). --> Bash Prompt パッケージは、<htmlurl url="http://bash.current.nu" name="http://bash.current.nu">で入手可能です。Rob Current (別名BadLandZ) を中心とした人たちの作品です。パッケージはまだ初期ベータ版の段階ですが、 様々なプロンプト(やテーマ)を(PS1文字列を ~/.bash_profile や ~/.bashrc に いれることにより)ログインシェルやサブシェルで使うことを可能にしてくれます。 多くのテーマは拡張 VGA 文字セットを使っていますので、(多くのシステムでは デフォルトにはなっていませんが) VGA フォントでないとうまく表示されません。 <sect1><!--Changing the Xterm Font-->Xterm のフォントを変える <p> <!-- To use some of the most attractive prompts in the Bash Prompt package, you need to get and install fonts that support the character sets expected by the prompts. These are referred to as "VGA Fonts," but I'm unclear on the distinction between them and the fonts Linux usually ships with - although clearly they support different character sets. Standard Xterm fonts support an extended alphabet, including a lot of letters with accents. In VGA fonts, this material is replaced by graphical characters - blocks, dots, lines. If anyone can explain this in more detail, e-mail me and I'll include the explanation here. --> Bash Prompt パッケージの多くの魅力的なプロンプトを使うには、プロンプトが 想定している文字セットに対応したフォントをインストールする必要があります。 これは VGA フォントと呼ばれていますが、これと Linux に通常ついてくるフォント との違いがよく分かりません。明らかに文字セットは違っていますが。標準の Xterm フォントは、拡張されたアルファベットを持っており、アクセントのついた 文字を含んでいます。VGA フォントではこのような文字を四角や点や線などの図形 文字に変えています。これについて詳しく説明できる方は私にメールして ください。ここに説明を入れます。 <p> <!-- Getting and installing these fonts is a somewhat involved process. First, retrieve the font(s). Next, ensure they're .pcf or .pcf.gz files. If they're .bdf files, investigate the "bdftopcf" command (ie. read the man page). Drop the .pcf or .pcf.gz files into the /usr/X11R6/lib/X11/fonts/misc dir (this is the correct directory for RedHat 5.1 and Slackware 3.4, it may be different on other distributions). "cd" to that directory, and run the "mkfontdir" command. Then run "xset fp rehash". Sometimes it's a good idea to go into the fonts.alias file in the same directory, and create shorter alias names for the fonts. --> これらのフォントを入手してインストールするにはちょっと手間がかかります。 まずフォントを入手します。これらが .pcf か .pcf.gz になっていることを確認 してください。もし .bdf になっていたら、bdftopcf コマンドを研究してください (man ページを読んで下さい)。.pcf や .pcf.gz ファイルを /usr/X11R6/lib/X11/fonts/misc ディレクトリに入れます(RedHat 5.1 や Slackware 3.4 ではこうなっていますが、 他の Linux ディストリビューションでは違うかもしれません)。 そのディレクトリに cd し、mkfontdir コマンドを実行します。次に xset fp rehash を実行します。同じディレクトリに ある fonts.alias ファイルを見て、フォントの別名を短く定義するのもいいでしょう。 <p> <!-- To use the new fonts, you start your Xterm program of choice with the appropriate command to your Xterm, which can be found either in the man page or by using the "-help" parameter on the command line. Popular terms would be used as follows: --> 新しいフォントを使うには適切に Xterm を起動する必要があります。man ページを みたり、xterm --help としてみてください。通常次のように起動します。 <tscreen><verb> xterm -font <fontname> </verb></tscreen> <bf>または</bf> <tscreen><verb> xterm -fn <fontname> -fb <fontname-bold> Eterm -f <fontname> rxvt -fn <fontname> </verb></tscreen> <p> <!-- VGA fonts are available from <em>Stumpy's ANSI Fonts</em> page at <htmlurl url="http://home.earthlink.net/~us5zahns/enl/ansifont.html" name="http://home.earthlink.net/~us5zahns/enl/ansifont.html"> (which I have borrowed from extensively while writing this). --> VGA フォントは、 <htmlurl url="http://home.earthlink.net/~us5zahns/enl/ansifont.html" name="http://home.earthlink.net/~us5zahns/enl/ansifont.html">の <em>Stumpy's ANSI Fonts</em>ページをみてください。(このページは この文書を書くのに大いに参照させてもらいました) <sect><!--Loading a Different Prompt-->プロンプトを変える <sect1><!--Loading a Different Prompt, Later-->プロンプトを変える、後で <p> <!-- The explanations in this HOWTO have shown how to make PS1 environment variables, or how to incorporate those PS1 and PS2 strings into functions that could be called by ~/.bashrc or as a theme by the bashprompt package. --> この HOWTO での説明で、環境変数 PS1 の作り方や、そのような PS1 や PS2 を ~/.bashrc で呼べる関数にいれたり、bashprompt パッケージのテーマとして いれる方法を示してきました。 <p> <!-- Using the bashprompt package, you would type <TT>bashprompt -i</TT> to see a list of available themes. To set the prompt in future login shells (primarily the console, but also telnet and Xterms, depending on how your Xterms are set up), you would type <TT>bashprompt -l themename</TT>. bashprompt then modifies your ~/.bash_profile to call the requested theme when it starts. To set the prompt in future subshells (usually Xterms, rxvt, etc.), you type <TT>bashprompt -s themename</TT>, and bashprompt modifies your ~/.bashrc file to call the appropriate theme at startup. --> bashprompt パッケージを使うのに、<TT>bashprompt -i</TT>とやれば登録されて いるテーマの一覧が出てきます。ログインシェルのプロンプトを設定するには <TT>bashprompt -l themename</TT>とします。bashprompt は、~/.bash_profile に必要なテーマを設定します。サブシェル用に設定するには、 <TT>bashprompt -s themename</TT>とすると、~/.bashrc が変更されます。 <p> <!-- See also <ref id="setps" name="Setting the PS? Strings Permanently"> for Johan Kullstam's note regarding the importance of putting the PS? strings in ~/.bashrc . --> <ref id="setps" name="PS? 文字列の設定を永続させる">の章には、~/.bashrcに PS? 文字列を置くことの重要性が書かれていますので、参照して下さい。 <sect1><!--Loading a Different Prompt, Immediately-->プロンプトを変える、今すぐ <p> <!-- You can change the prompt in your current terminal (using the example "elite" function above) by typing <TT>source elite</TT> followed by <TT>elite</TT> (assuming that the elite function file is the working directory). This is somewhat cumbersome, and leaves you with an extra function (elite) in your environment space - if you want to clean up the environment, you would have to type <TT>unset elite</TT> as well. This would seem like an ideal candidate for a small shell script, but a script doesn't work here because the script cannot change the environment of your current shell: it can only change the environment of the subshell it runs in. As soon as the script stops, the subshell goes away, and the changes the script made to the environment are gone. --> 現在の端末のプロンプトを変えるには、上の elite 関数の例を使えば、 <TT>source elite</TT>の後、<TT>elite</TT>とします(eliteファイルが 現ディレクトリにあるとして)。これは結構手間がかかります。環境にも elite関数が保存されてしまっていますが、これは<TT>unset elite</TT>で 解放することができます。シェルスクリプトで処理するのがいいと思うでしょうが、 ここではうまくいきません。スクリプトでは現在の環境を変えることが できないからです。スクリプトの動いているサブシェルの環境を変えるだけ です。スクリプトが終了すると、サブシェルも終了し、スクリプトによって 変化した環境は失われます。 <!-- What <bf>can</bf> change environment variables of your current shell are environment functions. The bashprompt package puts a function called "callbashprompt" into your environment, and, while they don't document it, it can be called to load any bashprompt theme on the fly. It looks in the theme directory it installed (the theme you're calling has to be there), sources the function you asked for, loads the function, and then unsets the function, thus keeping your environment uncluttered. "callbashprompt" wasn't intended to be used this way, and has no error checking, but if you keep that in mind, it works quite well. --> 現在のシェルの環境変数を変えるには、環境関数を用いる必要があります。 bashprompt パッケージでは、callbashprompt という関数が環境に呼び込まれます。 これについてのドキュメントはありませんが、この関数を使うとその場で bashprompt のテーマをロードすることができます。インストールされた テーマディレクトリに探しにいきますので、あなたが使いたいテーマ ファイルはこのディレクトリにいれておかなければなりません。ついで、 関数を解析し、実行し、メモリを解放します。環境領域はふくらんでいきません。 callbashprompt はこのような使われ方を想定していませんし、エラーチェックも 行ないませんが、そのことだけ覚えておけばうまくいきます。 <sect><!--Loading Prompt Colours Dynamically-->動的にプロンプトの色を変える <sect1><!--A "Proof of Concept" Example-->どうすれば可能か <p> <!-- This is a "proof of concept" more than an attractive prompt: changing colours within the prompt dynamically. In this example, the colour of the host name changes depending on the load (as a warning). --> これは魅力的なプロンプトというよりは、動的にプロンプトを変えるには こうすれば可能であるという例示です。この例では、ホスト名がシステム 負荷に応じて色を変えます(警告になります)。 <!-- <code> #!/bin/bash # "hostloadcolour" - 17 October 98, by Giles # # The idea here is to change the colour of the host name in the prompt, # depending on a threshold load value. # THRESHOLD_LOAD is the value of the one minute load (multiplied # by one hundred) at which you want # the prompt to change from COLOUR_LOW to COLOUR_HIGH THRESHOLD_LOAD=200 COLOUR_LOW='1;34' # light blue COLOUR_HIGH='1;31' # light red function prompt_command { ONE=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\1/" -e "s/ //g") # Apparently, "scale" in bc doesn't apply to multiplication, but does # apply to division. ONEHUNDRED=$(echo -e "scale=0 \n $ONE/0.01 \nquit \n" | bc) if [ $ONEHUNDRED -gt $THRESHOLD_LOAD ] then HOST_COLOUR=$COLOUR_HIGH # Light Red else HOST_COLOUR=$COLOUR_LOW # Light Blue fi } function hostloadcolour { PROMPT_COMMAND=prompt_command PS1="[$(date +%H%M)][\u@\[\033[\$(echo -n \$HOST_COLOUR)m\]\h\[\033[0;37m\]:\w]$ " } </code> --> <code> #!/bin/bash # "hostloadcolour" - 17 October 98, by Giles # # この例は、プロンプトのホスト名を負荷の値によって変えます。 # THRESHOLD_LOAD は、プロンプトの色を COLOUR_LOW から COLOUR_HIGH に # 変える1分間の負荷量(の100倍)を示します。 THRESHOLD_LOAD=200 COLOUR_LOW='1;34' # ライトブルー COLOUR_HIGH='1;31' # ライトレッド function prompt_command { ONE=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\1/" -e "s/ //g") # bcのscaleは、乗算には適用されず、除算に適用されるようです。 ONEHUNDRED=$(echo -e "scale=0 \n $ONE/0.01 \nquit \n" | bc) if [ $ONEHUNDRED -gt $THRESHOLD_LOAD ] then HOST_COLOUR=$COLOUR_HIGH # ライトレッド else HOST_COLOUR=$COLOUR_LOW # ライトブルー fi } function hostloadcolour { PROMPT_COMMAND=prompt_command PS1="[$(date +%H%M)][\u@\[\033[\$(echo -n \$HOST_COLOUR)m\]\h\[\033[0;37m\]:\w]$ " } </code> <p> <!-- Using your favorite editor, save this to a file named "hostloadcolour". If you have the Bashprompt package installed, this will work as a theme. If you don't, type <TT>source hostloadcolour</TT> and then <TT>hostloadcolour</TT>. Either way, "prompt_command" becomes a function in your environment. If you examine the code, you will notice that the colours ($COLOUR_HIGH and $COLOUR_LOW) are set using only a partial colour code, ie. "1;34" instead of "\[\033[1;34m\]", which I would have preferred. I have been unable to get it to work with the complete code. Please let me know if you manage this. --> 好みのエディタを使って、これを hostloadcolour というファイルに保存します。 Bashprompt パッケージがインストールされているなら、これはテーマファイルに なります。もしインストールしていないなら、<TT>source hostloadcolour</TT> に続いて、<TT>hostloadcolour</TT>とします。どちらにしても prompt_command が あなたの環境の関数になります。コードをみると、色($COLOUR_HIGHと$COLOUR_LOW) は色コードの一部つまり"\[\033[1;34m\]"(こうしたかったのですが)ではなく "1;34"で定義されていることに気づくでしょう。完全な色コードを使いたかった のですが、動きませんでした。どうしたらいいか分かったら教えてください。 <!-- ********************************** * * * Examples Start Here * * * ********************************** --> <sect><!--Example Prompts-->プロンプトの例 <sect1><!--A "Lightweight" Prompt-->「軽量」プロンプト <p> <code> function proml { local BLUE="\[\033[0;34m\]" local RED="\[\033[0;31m\]" local LIGHT_RED="\[\033[1;31m\]" local WHITE="\[\033[1;37m\]" local LIGHT_GRAY="\[\033[0;37m\]" case $TERM in xterm*) TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) TITLEBAR="" ;; esac PS1="${TITLEBAR}\ $BLUE[$RED\$(date +%H%M)$BLUE]\ $BLUE[$LIGHT_RED\u@\h:\w$BLUE]\ $WHITE\$$LIGHT_GRAY " PS2='> ' PS4='+ ' } </code> <sect1><!--Elite from Bashprompt Themes-->Bashpromptからelite <p> <!-- Note that this requires a VGA font. --> VGA フォントが必要です。 <code> # Created by KrON from windowmaker on IRC # Changed by Spidey 08/06 function elite { PS1="\[\033[31m\]\332\304\[\033[34m\](\[\033[31m\]\u\[\033[34m\]@\[\033[31m\]\h\ \[\033[34m\])\[\033[31m\]-\[\033[34m\](\[\033[31m\]\$(date +%I:%M%P)\ \[\033[34m\]-:-\[\033[31m\]\$(date +%m)\[\033[34m\033[31m\]/\$(date +%d)\ \[\033[34m\])\[\033[31m\]\304-\[\033[34m]\\371\[\033[31m\]-\371\371\ \[\033[34m\]\372\n\[\033[31m\]\300\304\[\033[34m\](\[\033[31m\]\W\[\033[34m\])\ \[\033[31m\]\304\371\[\033[34m\]\372\[\033[00m\]" PS2="> " } </code> <sect1><!--A "Power User" Prompt-->「パワーユーザー」プロンプト <p> <!-- I actually do use this prompt, but it results in noticeable delays in the appearance of the prompt on a single-user PII-400, so I wouldn't recommend using it on a multi-user P-100 or anything ... Look at it for ideas, rather than as a practical prompt. --> 私が実際に使っているプロンプトです。シングルユーザーの PentiumII-400MHz でもプロンプト表示の遅れが出ますので、マルチユーザーの Pentium-100MHz で 使うのはやめておいた方が...。実際に使うというよりは、考え方の例として 見てください。 <p> <![IGNORE[ <code> #!/bin/bash #---------------------------------------------------------------------- # POWER USER PROMPT "pprom2" #---------------------------------------------------------------------- # # Created August 98, Last Modified 9 November 98 by Giles # # Problem: when load is going down, it says "1.35down-.08", get rid # of the negative # - limit the length of the $PWD to 30 chars - right-truncate if # it exceeds that function prompt_command { # Create TotalMeg variable: sum of visible file sizes in current directory local TotalBytes=0 for Bytes in $(ls -l | grep "^-" | cut -c30-41) do let TotalBytes=$TotalBytes+$Bytes done TotalMeg=$(echo -e "scale=3 \nx=$TotalBytes/1048576\n if (x<1) {print \"0\"} \n print x \nquit" | bc) # This is used to calculate the differential in load values # provided by the "uptime" command. "uptime" gives load # averages at 1, 5, and 15 minute marks. # local one=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\1/" -e "s/ //g") local five=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\).*/\2/" -e "s/ //g") local diff1_5=$(echo -e "scale = scale ($one) \nx=$one - $five\n if (x>0) {print \"up\"} else {print \"down\"}\n print x \nquit \n" | bc) loaddiff="$(echo -n "${one}${diff1_5}")" # Count visible files: let files=$(ls -l | grep "^-" | wc -l | tr -d " ") let hiddenfiles=$(ls -l -d .* | grep "^-" | wc -l | tr -d " ") let executables=$(ls -l | grep ^-..x | wc -l | tr -d " ") let directories=$(ls -l | grep "^d" | wc -l | tr -d " ") let hiddendirectories=$(ls -l -d .* | grep "^d" | wc -l | tr -d " ")-2 let linktemp=$(ls -l | grep "^l" | wc -l | tr -d " ") if [ "$linktemp" -eq "0" ] then links="" else links=" ${linktemp}l" fi unset linktemp let devicetemp=$(ls -l | grep "^[bc]" | wc -l | tr -d " ") if [ "$devicetemp" -eq "0" ] then devices="" else devices=" ${devicetemp}bc" fi unset devicetemp } PROMPT_COMMAND=prompt_command function pprom2 { local BLUE="\[\033[0;34m\]" local LIGHT_GRAY="\[\033[0;37m\]" local LIGHT_GREEN="\[\033[1;32m\]" local LIGHT_BLUE="\[\033[1;34m\]" local LIGHT_CYAN="\[\033[1;36m\]" local YELLOW="\[\033[1;33m\]" local WHITE="\[\033[1;37m\]" local RED="\[\033[0;31m\]" case $TERM in xterm*) TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) TITLEBAR="" ;; esac PS1="$TITLEBAR\ $BLUE[$RED\$(date +%H%M)$BLUE]\ $BLUE[$RED\u@\h$BLUE]\ $BLUE[\ $LIGHT_GRAY\${files}.\${hiddenfiles}-\ $LIGHT_GREEN\${executables}x \ $LIGHT_GRAY(\${TotalMeg}Mb) \ $LIGHT_BLUE\${directories}.\ \${hiddendirectories}d\ $LIGHT_CYAN\${links}\ $YELLOW\${devices}\ $BLUE]\ $BLUE[${WHITE}\${loaddiff}$BLUE]\ $BLUE[\ $WHITE\$(ps ax | wc -l | sed -e \"s: ::g\")proc\ $BLUE]\ \n\ $BLUE[$RED\$PWD$BLUE]\ $WHITE\$\ \ $LIGHT_GRAY " PS2='> ' PS4='+ ' } ]]> <code> #!/bin/bash #---------------------------------------------------------------------- # POWER USER PROMPT "pprom2" #---------------------------------------------------------------------- # # Created August 98, Last Modified 9 November 98 by Giles # # 問題:負荷が下がった時 "1.35down-.08" となるので、- をとる必要がある。 # - $PWD の長さを30文字までとし、超えた部分は右を切り捨てている。 function prompt_command { # 変数 TotalMeg は現ディレクトリの可視ファイルのサイズの合計 local TotalBytes=0 for Bytes in $(ls -l | grep "^-" | cut -c30-41) do let TotalBytes=$TotalBytes+$Bytes done TotalMeg=$(echo -e "scale=3 \nx=$TotalBytes/1048576\n if (x<1) {print \"0\"} \n print x \nquit" | bc) # uptime コマンドにより、負荷の差分を計算。 # uptime は、1分、5分、15分の平均負荷を示す。 # local one=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\1/" -e "s/ //g") local five=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\).*/\2/" -e "s/ //g") local diff1_5=$(echo -e "scale = scale ($one) \nx=$one - $five\n if (x>0) {print \"up\"} else {print \"down\"}\n print x \nquit \n" | bc) loaddiff="$(echo -n "${one}${diff1_5}")" # 可視ファイルの数を数える let files=$(ls -l | grep "^-" | wc -l | tr -d " ") let hiddenfiles=$(ls -l -d .* | grep "^-" | wc -l | tr -d " ") let executables=$(ls -l | grep ^-..x | wc -l | tr -d " ") let directories=$(ls -l | grep "^d" | wc -l | tr -d " ") let hiddendirectories=$(ls -l -d .* | grep "^d" | wc -l | tr -d " ")-2 let linktemp=$(ls -l | grep "^l" | wc -l | tr -d " ") if [ "$linktemp" -eq "0" ] then links="" else links=" ${linktemp}l" fi unset linktemp let devicetemp=$(ls -l | grep "^[bc]" | wc -l | tr -d " ") if [ "$devicetemp" -eq "0" ] then devices="" else devices=" ${devicetemp}bc" fi unset devicetemp } PROMPT_COMMAND=prompt_command function pprom2 { local BLUE="\[\033[0;34m\]" local LIGHT_GRAY="\[\033[0;37m\]" local LIGHT_GREEN="\[\033[1;32m\]" local LIGHT_BLUE="\[\033[1;34m\]" local LIGHT_CYAN="\[\033[1;36m\]" local YELLOW="\[\033[1;33m\]" local WHITE="\[\033[1;37m\]" local RED="\[\033[0;31m\]" case $TERM in xterm*) TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) TITLEBAR="" ;; esac PS1="$TITLEBAR\ $BLUE[$RED\$(date +%H%M)$BLUE]\ $BLUE[$RED\u@\h$BLUE]\ $BLUE[\ $LIGHT_GRAY\${files}.\${hiddenfiles}-\ $LIGHT_GREEN\${executables}x \ $LIGHT_GRAY(\${TotalMeg}Mb) \ $LIGHT_BLUE\${directories}.\ \${hiddendirectories}d\ $LIGHT_CYAN\${links}\ $YELLOW\${devices}\ $BLUE]\ $BLUE[${WHITE}\${loaddiff}$BLUE]\ $BLUE[\ $WHITE\$(ps ax | wc -l | sed -e \"s: ::g\")proc\ $BLUE]\ \n\ $BLUE[$RED\$PWD$BLUE]\ $WHITE\$\ \ $LIGHT_GRAY " PS2='> ' PS4='+ ' } </code> <sect1><!--A Prompt the Width of Your Term-->端末幅のプロンプト <p> <!-- A friend complained that he didn't like having a prompt that kept changing size because it had $PWD in it, so I wrote this prompt that adjusts its size to exactly the width of your term. --> プロンプトに $PWD が含まれると、プロンプトの長さが変わるとなげく友人がいた ので、プロンプトの長さがちょうど端末の幅になるプロンプトを書いてみました。 <![IGNORE[ <code> #!/bin/bash # termwide prompt # by Giles - created 2 November 98 # last modified 9 November 98 # # The idea here is to have the upper line of this two line prompt # always be the width of your term. Do this by calculating the # width of the text elements, and putting in fill as appropriate # or right-truncating $PWD. # # - needs a lot of refinement, but it works # - host doesn't need to be figured out every time: that's a # constant # - what about username? could change? # - text vars generated by prompt_command can't be locals, # because they have to go to PS1. function prompt_command { TERMWIDTH=${COLUMNS} # Calculate the width of the prompt: hostnam=$(echo -n $HOSTNAME | sed -e "s/[\.].*//") let hostsize=$(echo -n $hostnam | wc -c | tr -d " ") # "whoami" and "pwd" include a trailing newline usernam=$(whoami) let usersize=$(echo -n $usernam | wc -c | tr -d " ") newPWD="${PWD}" let pwdsize=$(echo -n ${newPWD} | wc -c | tr -d " ") # Add all the accessories below ... let promptsize=$(echo -n "--(${usernam}@${hostnam})---(${PWD})--" \ | wc -c | tr -d " ") let fillsize=${TERMWIDTH}-${promptsize} fill="" while [ "$fillsize" -gt "0" ] do fill="${fill}-" let fillsize=${fillsize}-1 done if [ "$fillsize" -lt "0" ] then let cut=((${fillsize})*(-1))+3 sedvar="" while [ "$cut" -gt "0" ] do sedvar="${sedvar}." let cut=${cut}-1 done newPWD="...$(echo -n $PWD | sed -e "s/\(^${sedvar}\)\(.*\)/\2/")" fi } PROMPT_COMMAND=prompt_command function termwide { local GRAY="\[\033[1;30m\]" local LIGHT_GRAY="\[\033[0;37m\]" local WHITE="\[\033[1;37m\]" local LIGHT_BLUE="\[\033[1;34m\]" local YELLOW="\[\033[1;33m\]" case $TERM in xterm*) TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) TITLEBAR="" ;; esac PS1="$TITLEBAR\ $YELLOW-$LIGHT_BLUE-(\ $YELLOW\${usernam}$LIGHT_BLUE@$YELLOW\${hostnam}\ ${LIGHT_BLUE})-${YELLOW}-\${fill}${LIGHT_BLUE}-(\ $YELLOW\${newPWD}\ $LIGHT_BLUE)-$YELLOW-\ \n\ $YELLOW-$LIGHT_BLUE-(\ $YELLOW\$(date +%H%M)$LIGHT_BLUE:$YELLOW\$(date \"+%a,%d %b %y\")\ $LIGHT_BLUE:$WHITE\$$LIGHT_BLUE)-\ $YELLOW-\ $LIGHT_GRAY " PS2="$LIGHT_BLUE-$YELLOW-$YELLOW-$LIGHT_GRAY " } ]]> <code> #!/bin/bash # 端末幅のプロンプト # by Giles - created 2 November 98 # last modified 9 November 98 # # ここで考えたのは、2行からなるプロンプトの1行目が端末の幅になるように # することです。そうするために、テキストの文字数を数え、幅に合うように # $PWD を補ったり、右を切り詰めたりします。 # # - もっと洗練させる必要がありますが、とりあえず動きます。 # - ホスト名は毎回さがす必要がありません。変化しませんから。 # - ユーザー名はどうだろう? 変わるかなあ? # - prompt_command で作られるテキスト変数は局所変数ではいけない。 # PS1 に保存される必要があるから。 function prompt_command { TERMWIDTH=${COLUMNS} # プロンプト幅を計算 hostnam=$(echo -n $HOSTNAME | sed -e "s/[\.].*//") let hostsize=$(echo -n $hostnam | wc -c | tr -d " ") # "whoami" と "pwd" の最後は改行になっている。 usernam=$(whoami) let usersize=$(echo -n $usernam | wc -c | tr -d " ") newPWD="${PWD}" let pwdsize=$(echo -n ${newPWD} | wc -c | tr -d " ") # アクセサリをつけていく let promptsize=$(echo -n "--(${usernam}@${hostnam})---(${PWD})--" \ | wc -c | tr -d " ") let fillsize=${TERMWIDTH}-${promptsize} fill="" while [ "$fillsize" -gt "0" ] do fill="${fill}-" let fillsize=${fillsize}-1 done if [ "$fillsize" -lt "0" ] then let cut=((${fillsize})*(-1))+3 sedvar="" while [ "$cut" -gt "0" ] do sedvar="${sedvar}." let cut=${cut}-1 done newPWD="...$(echo -n $PWD | sed -e "s/\(^${sedvar}\)\(.*\)/\2/")" fi } PROMPT_COMMAND=prompt_command function termwide { local GRAY="\[\033[1;30m\]" local LIGHT_GRAY="\[\033[0;37m\]" local WHITE="\[\033[1;37m\]" local LIGHT_BLUE="\[\033[1;34m\]" local YELLOW="\[\033[1;33m\]" case $TERM in xterm*) TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) TITLEBAR="" ;; esac PS1="$TITLEBAR\ $YELLOW-$LIGHT_BLUE-(\ $YELLOW\${usernam}$LIGHT_BLUE@$YELLOW\${hostnam}\ ${LIGHT_BLUE})-${YELLOW}-\${fill}${LIGHT_BLUE}-(\ $YELLOW\${newPWD}\ $LIGHT_BLUE)-$YELLOW-\ \n\ $YELLOW-$LIGHT_BLUE-(\ $YELLOW\$(date +%H%M)$LIGHT_BLUE:$YELLOW\$(date \"+%a,%d %b %y\")\ $LIGHT_BLUE:$WHITE\$$LIGHT_BLUE)-\ $YELLOW-\ $LIGHT_GRAY " PS2="$LIGHT_BLUE-$YELLOW-$YELLOW-$LIGHT_GRAY " } </code> <sect1>役立たずのエレガントな時刻表示プロンプト<label id="clock3"> <!-- Don't change this section title without changing the name= tag that refers to it. The pointer is in the section on cursor movement. --> <p> <!-- This is probably the single most attractive (and useless) prompt I've ever created. Because many X terminal emulators don't implement cursor position save and restore, the alternative when putting a clock in the upper right corner is to anchor the cursor at the bottom of the terminal. This builds on the idea of the "termwide" prompt above, drawing a line up the right side of the screen from the prompt to the clock. A VGA font is required. --> これは私が作ったプロンプトの中で、おそらくもっとも魅力的な(もっとも役立たない) ものです。多くのX端末エミュレータは、カーソル位置の記憶と復旧を実現して いませんので、時刻を右上に置くためにカーソルを端末の最下行に固定しています。 このプロンプトは、上の端末幅のプロンプトのアイディアを使っており、画面の 右端にプロンプトから時刻表示のところまで直線を引いています。VGA フォントが 必要です。 <p> <!-- Note: There is an odd substitution in here, that may not print properly being translated from SGML to other formats: I had to substitute the screen character for \304 - I would normally have just included the sequence "\304", but it was necessary to make this substitution in this case. --> 注意: ここでは変な置換が使われていますので、SGML から他のフォーマットに 変えた時にきちんと表示されないかもしれません。\304の文字を置換する必要が ありました。通常は"\304"でいいのですが、ここではこのような置換をすることが 必要でした。 <![IGNORE[ <code> #!/bin/bash <!-- # This prompt requires a VGA font. The prompt is anchored at the bottom # of the terminal, fills the width of the terminal, and draws a line up # the right side of the terminal to attach itself to a clock in the upper # right corner of the terminal. --> # このプロンプトは VGA フォントを必要とする。プロンプトは端末の一番下の行に # 端末幅一杯に表示され、画面の右端に直線を表示し、右上の時刻表示につながっ # ている。 function prompt_command { # Calculate the width of the prompt: hostnam=$(echo -n $HOSTNAME | sed -e "s/[\.].*//") <!-- # "whoami" and "pwd" include a trailing newline --> # "whoami"と"pwd"は最後に改行を含んでいる。 usernam=$(whoami) newPWD="${PWD}" <!-- # Add all the accessories below ... --> # すべてのアクセサリを以下に加える。 let promptsize=$(echo -n "--(${usernam}@${hostnam})---(${PWD})-----" \ | wc -c | tr -d " ") <!-- # Figure out how much to add between user@host and PWD (or how much to # remove from PWD) --> # user@host と PWD の間にどれだけ加えればいいか(PWD から切り取ればよいか)を # 計算する。 let fillsize=${COLUMNS}-${promptsize} fill="" <!-- # Make the filler if prompt isn't as wide as the terminal: --> # プロンプトが端末幅より短い場合には、埋め草を作る。 while [ "$fillsize" -gt "0" ] do fill="${fill}" <!-- # The A with the umlaut over it (it will appear as a long dash if # you're using a VGA font) is \304, but I cut and pasted it in # because Bash will only do one substitution - which in this case is # putting $fill in the prompt. --> # A ウムラウト(VGA フォントでは長い横線)は\304ですが、Bash では置換は # 一種類しか行なわれず、ここでは $fill をプロンプトに埋め込むことな # ので、このように変えました。 let fillsize=${fillsize}-1 done <!-- # Right-truncate PWD if the prompt is going to be wider than the terminal: --> # プロンプトが端末幅より長過ぎるようなら、PWD の右を切り捨てます。 if [ "$fillsize" -lt "0" ] then let cutt=3-${fillsize} sedvar="" while [ "$cutt" -gt "0" ] do sedvar="${sedvar}." let cutt=${cutt}-1 done newPWD="...$(echo -n $PWD | sed -e "s/\(^${sedvar}\)\(.*\)/\2/")" fi # <!-- # Create the clock and the bar that runs up the right side of the term --> # 時刻と端末の右端に表示するバーを作ります。 # local LIGHT_BLUE="\033[1;34m" local YELLOW="\033[1;33m" <!-- # Position the cursor to print the clock: --> # 時刻を表示するカーソルの位置を決めます。 echo -en "\033[2;$((${COLUMNS}-9))H" echo -en "$LIGHT_BLUE($YELLOW$(date +%H%M)$LIGHT_BLUE)\304$YELLOW\304\304\277" local i=${LINES} echo -en "\033[2;${COLUMNS}H" <!-- # Print vertical dashes down the side of the terminal: --> # 縦線を端末の脇に表示します。 while [ $i -ge 4 ] do echo -en "\033[$(($i-1));${COLUMNS}H\263" let i=$i-1 done let prompt_line=${LINES}-1 <!-- # This is needed because doing \${LINES} inside a Bash mathematical # expression (ie. $(())) doesn't seem to work. --> # Bashの数式表現($(()))の中では、\${LINES}がうまく機能しないようなので } PROMPT_COMMAND=prompt_command function clock3 { local LIGHT_BLUE="\[\033[1;34m\]" local YELLOW="\[\033[1;33m\]" local WHITE="\[\033[1;37m\]" local LIGHT_GRAY="\[\033[0;37m\]" local NO_COLOUR="\[\033[0m\]" case $TERM in xterm*) TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) TITLEBAR="" ;; esac PS1="$TITLEBAR\ \[\033[\${prompt_line};0H\] $YELLOW\332$LIGHT_BLUE\304(\ $YELLOW\${usernam}$LIGHT_BLUE@$YELLOW\${hostnam}\ ${LIGHT_BLUE})\304${YELLOW}\304\${fill}${LIGHT_BLUE}\304(\ $YELLOW\${newPWD}\ $LIGHT_BLUE)\304$YELLOW\304\304\304\331\ \n\ $YELLOW\300$LIGHT_BLUE\304(\ $YELLOW\$(date \"+%a,%d %b %y\")\ $LIGHT_BLUE:$WHITE\$$LIGHT_BLUE)\304\ $YELLOW\304\ $LIGHT_GRAY " PS2="$LIGHT_BLUE\304$YELLOW\304$YELLOW\304$NO_COLOUR " } </code> ]]> <code> #!/bin/bash # このプロンプトは VGA フォントを必要とする。プロンプトは端末の一番下の行に # 端末幅一杯に表示され、画面の右端に直線を表示し、右上の時刻表示につながっ # ている。 function prompt_command { # Calculate the width of the prompt: hostnam=$(echo -n $HOSTNAME | sed -e "s/[\.].*//") # "whoami"と"pwd"は最後に改行を含んでいる。 usernam=$(whoami) newPWD="${PWD}" # すべてのアクセサリを以下に加える。 let promptsize=$(echo -n "--(${usernam}@${hostnam})---(${PWD})-----" \ | wc -c | tr -d " ") # user@host と PWD の間にどれだけ加えればいいか(PWD から切り取ればよいか)を # 計算する。 let fillsize=${COLUMNS}-${promptsize} fill="" # プロンプトが端末幅より短い場合には、埋め草を作る。 while [ "$fillsize" -gt "0" ] do fill="${fill}" # A ウムラウト(VGA フォントでは長い横線)は\304ですが、Bash では置換は # 一種類しか行なわれず、ここでは $fill をプロンプトに埋め込むことな # ので、このように変えました。 let fillsize=${fillsize}-1 done # プロンプトが端末幅より長過ぎるようなら、PWD の右を切り捨てます。 if [ "$fillsize" -lt "0" ] then let cutt=3-${fillsize} sedvar="" while [ "$cutt" -gt "0" ] do sedvar="${sedvar}." let cutt=${cutt}-1 done newPWD="...$(echo -n $PWD | sed -e "s/\(^${sedvar}\)\(.*\)/\2/")" fi # # 時刻と端末の右端に表示するバーを作ります。 # local LIGHT_BLUE="\033[1;34m" local YELLOW="\033[1;33m" # 時刻を表示するカーソルの位置を決めます。 echo -en "\033[2;$((${COLUMNS}-9))H" echo -en "$LIGHT_BLUE($YELLOW$(date +%H%M)$LIGHT_BLUE)\304$YELLOW\304\304\277" local i=${LINES} echo -en "\033[2;${COLUMNS}H" # 縦線を端末の脇に表示します。 while [ $i -ge 4 ] do echo -en "\033[$(($i-1));${COLUMNS}H\263" let i=$i-1 done let prompt_line=${LINES}-1 # Bashの数式表現($(()))の中では、\${LINES}がうまく機能しないようなので } PROMPT_COMMAND=prompt_command function clock3 { local LIGHT_BLUE="\[\033[1;34m\]" local YELLOW="\[\033[1;33m\]" local WHITE="\[\033[1;37m\]" local LIGHT_GRAY="\[\033[0;37m\]" local NO_COLOUR="\[\033[0m\]" case $TERM in xterm*) TITLEBAR='\[\033]0;\u@\h:\w\007\]' ;; *) TITLEBAR="" ;; esac PS1="$TITLEBAR\ \[\033[\${prompt_line};0H\] $YELLOW\332$LIGHT_BLUE\304(\ $YELLOW\${usernam}$LIGHT_BLUE@$YELLOW\${hostnam}\ ${LIGHT_BLUE})\304${YELLOW}\304\${fill}${LIGHT_BLUE}\304(\ $YELLOW\${newPWD}\ $LIGHT_BLUE)\304$YELLOW\304\304\304\331\ \n\ $YELLOW\300$LIGHT_BLUE\304(\ $YELLOW\$(date \"+%a,%d %b %y\")\ $LIGHT_BLUE:$WHITE\$$LIGHT_BLUE)\304\ $YELLOW\304\ $LIGHT_GRAY " PS2="$LIGHT_BLUE\304$YELLOW\304$YELLOW\304$NO_COLOUR " } </code> 翻訳 遠藤 明 akendo@t3.rim.or.jp 校正協力 yuri aisaka <ayqw@mail2.alpha-net.or.jp> HASEGAWA Yasushi <yaz-hase@qb3.so-net.ne.jp> </article>