bashのヘルプ・マニュアル
日本語 英語
bash --help
GNU bash, version 4.1.2(2)-release-(x86_64-redhat-linux-gnu)
使用方法: bash [GNU 長いオプション] [オプション] ...
bash [GNU 長いオプション] [オプション] スクリプトファイル ...
GNU 長いオプション:
--debug
--debugger
--dump-po-strings
--dump-strings
--help
--init-file
--login
--noediting
--noprofile
--norc
--posix
--protected
--rcfile
--rpm-requires
--restricted
--verbose
--version
シェル オプション:
-irsD or -c command or -O shopt_option (invocation only)
-abefhkmnptuvxBCHP 又は -o オプション
シェルオプションの詳細については `bash -c "help set"'と入力.
組み込みコマンドについては `bash -c help'と入力 .
GNU bash, version 4.1.2(2)-release-(x86_64-redhat-linux-gnu)
Usage: bash [GNU long option] [option] ...
bash [GNU long option] [option] script-file ...
GNU long options:
--debug
--debugger
--dump-po-strings
--dump-strings
--help
--init-file
--login
--noediting
--noprofile
--norc
--posix
--protected
--rcfile
--rpm-requires
--restricted
--verbose
--version
Shell options:
-irsD or -c command or -O shopt_option (invocation only)
-abefhkmnptuvxBCHP or -o option
Type `bash -c "help set"' for more information about shell options.
Type `bash -c help' for more information about shell builtin commands.
man bash
BASH(1) BASH(1)
名前
bash - GNU Bourne-Again SHell
書式
bash [options] [file]
著作権
Bash is Copyright (C) 1989-2001 by the Free Software Foundation, Inc.
説明
bash は、標準入力やファイルから読み込んだコマンドを実行する、 sh 互換の
コマンド言語インタプリタです。 bash には、Korn シェルや C シェ ル (ksh
や csh) の便利な機能も採り入れられています。
bash は IEEE POSIX Shell and Tools specification (IEEE Working Group
1003.2) に準拠する実装を目指しています。
オプション
bash は以下のオプションを起動時に解釈します (組み込みコマンド set の 説
明で述べられている 1 文字のシェルオプションも使えます):
-c string -c オプションが指定されると、コマンドが string から読み込まれ
ます。 string の後に引き数があれば、これらは位置パラ メ ー タ
(positional parameter: $0 からはじまるパラメータ) に代入され
ます。
-r -r オプションが指定されると、 bash は 制 限 さ れ た 状 態
(restricted) となります (後述の 制限付きのシェルを参照)。
-i -i オプションが指定されると、 bash は 対話的 (interactive) に
動作します。
-s -s オプションが指定された場合と、オプションをすべて処理した後
に 引き数が残っていなかった場合には、コマンドは標準入力から読
み込まれます。このオプションを使うと、対話的シェルを起動す る
ときに位置パラメータを設定できます。
-D 二 重引用符によるクォート文字列 (double-quoted strings) に $
が前置されたものを、全てリストして標準出力に出力します。こ れ
ら は、カレントロケールが C または POSIX 以外の時に、翻訳の対
象となるべき文字列です。このオプションを指定すると、自動的 に
-n オプションも指定されたことになります。つまりコマンドは全く
実行されません。
-- -- はオプションの終わりを示し、それ以降のオプション処理を行い
ま せん。 -- 以降の引き数は全て、ファイル名や引き数として扱わ
れます。引き数 - は -- と同じです。
bash が解釈するオプションには複数の文字からなるものもたくさんあります。
このようなオプションを認識させるためには、コマンドライン中で 1 文字のオ
プションよりも前に置かなければなりません。
--dump-po-strings
-D と同じですが、出力は GNU gettext の po (ポータブルオブジェ ク
ト) ファイル形式で行われます。
--dump-strings
-D と同じです。
--help 使用方法についてのメッセージを標準出力に表示し、正常終了します。
--init-file file
--rcfile file
対話的シェルとして起動された場合、個人用 の 初 期 化 フ ァ イ ル
~/.bashrc の代わりに file からコマンドを実行します (後述の 起動
セクションを参照)。
--login
ログインシェル (後述の 起動セクションを参照) として起動された か
のように bash を動作させます。
--noediting
シ ェ ル が 対話的動作の場合、コマンドラインを読み込むときに GNU
readline ライブラリを使用しません。
--noprofile
システム全体用の起動ファイル /etc/profile および個人用の初期化フ
ァイル ~/.bash_profile, ~/.bash_login, ~/.profile のいずれも読み
込みません。デフォルトでは、 bash はログインシェルとして起動され
た 時にこれらのファイルを読み込みます (後述の 起動セクションを参
照)。
--norc シェルが対話的動作を行う場合に、個人用初期化ファイ ル ~/.bashrc
の読み込み・実行を行いません。シェルが sh として起動された場合に
は、このオプションはデフォルトで有効になります。
--posix
bash の動作のうち、デフォルトの振舞いが POSIX 1003.2 の標準と 異
なる部分を、標準に適合するように変更します (posix モード)。
--restricted
シ ェルの動作を制限します (後述の 制限付きのシェルセクションを参
照)。
--verbose
-v と同じです。
--version
実行された bash のバージョン情報を標準出力に表示し、正常終了しま
す。
引き数
オ プション処理の後に引き数が残っており、かつ -c オプションと -s オプシ
ョンのいずれも指定されていない場合、最初の引き数はファイル名とみなさ れ
、 そのファイルにシェルコマンドが記述されているとみなされます。このよう
に bash が起動された場合、 $0 にそのファイルの名前が設定されます (残 り
の引き数は位置パラメータに設定されます)。 bash はこのファイルからコマン
ドの読み込みと実行を行い、そして終了します。 bash の終了ステータスは 、
こ のスクリプト中で実行された最後のコマンドの終了ステータスになります。
コマンドが全く実行されなければ、終了ステータスは 0 です。
起動
ログインシェル(login shell)とは、0 番目の引き数の最初の文字が - であ る
シェル、または --login オプション付きで起動されたシェルのことです。
対 話的なシェルとは、オプションでない引数がなく、標準入力と標準出力がい
ずれも端末に接続されていて (これは isatty(3) で調べられます)、 -c オ プ
シ ョンが指定されていない状態で起動されたシェル、または -i オプション付
きで起動されたシェルのことです。 bash が対話的に動作している場合には 、
PS1 が設定され、 $- に i が含まれます。これを利用すると、対話的動作の状
態であるかどうかを、シェルスクリプトや起動ファイルの内部で調べられま す
。
以 下の段落では、 bash がどのように起動ファイルを実行するかを説明します
。以下のファイルのいずれかが、「存在しているが読み込みできない」場合 は
、 bash はエラーを報告します。ファイル名に含まれるチルダは、後述の 展開
セクションにおける チルダ展開の項目で述べるように展開されます。
bash が対話的なログインシェルとして起動されるか、 --login オプション 付
き の非対話的シェルとして起動されると、 /etc/profile ファイルが存在すれ
ば、 bash はまずここからコマンドを読み込んで実行します。このファイル を
読 んだ後、 bash は ~/.bash_profile, ~/.bash_login, ~/.profile をこの順
番で探します。 bash は、この中で最初に見つかり、かつ読み込みが可能で あ
るファイルからコマンドを読み込んで実行します。 --noprofile オプションを
使ってシェルを起動すれば、この動作を行わないようにできます。
ログインシェルが終了するときには、 ~/.bash_logout ファイルがあ れ ば 、
bash はこれを読み込んで実行します。
ログインシェルでない対話的シェルとして起動されると、 ~/.bashrc ファイル
があれば、 bash はここからコマンドを読み込み、実行します。この 動 作 は
--norc オプションで行わないようにできます。 --rcfile file オプションを
使うと、コマンドの読み込みと実行を ~/.bashrc からでなく file から行わせ
ることができます。
( 例えばシェルスクリプトを実行するために) 非対話的に起動されると、 bash
は環境変数 BASH_ENV を調べ、この変数が定義されていればその値を展開し 、
得 られた値をファイル名とみなして、そこからコマンドの読み込みと実行を行
います。つまり bash は以下のコマンドが実行されたのと同じように動作し ま
す:
if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
た だし、ファイル名を探すために PATH 環境変数の値が使われることはありま
せん。
sh という名前で bash を起動すると、 bash は古くからある sh の起動動作を
できるだけ真似しようとします。また POSIX 標準にもできるだけ従おうとしま
す。対話的なログインシェルとして起動されると、あるいは --login オプショ
ン付きの非対話的シェルとして起動されると、このシェルはまず /etc/profile
と ~/.profile の順でコマンドの読み込みと実行をしようとします。 --nopro-
file オプションを使うと、この動作を行わないようにできます。 sh という名
前の対話的シェルとして起動されると、 bash は環境変数 ENV を調べ、この変
数 が定義されていればその値を展開し、展開で得た値をコマンドの読み込みと
実行を行うためのファイル名として使います。 sh という名前で起動された シ
ェ ルは、他の起動ファイルからコマンドの読み込みと起動を行うことはないの
で、 --rcfile オプションは全く効果を持ちません。 sh という名前の非対 話
的 シェルとして起動されると、このシェルは他の起動ファイルを何も読み込み
ません。 sh として起動された場合、 bash は起動ファイルの読み込みを行 っ
た後に POSIX モードに入ります。
--posix コマンドラインオプション等により bash が POSIX モードで起動され
ると、 bash は起動ファイルに関して POSIX 標準に従います。このモードでは
、対話的シェルは ENV 環境変数を展開し、展開して得られた名前のファイルか
らコマンドの読み込みと実行を行います。他の起動ファイルは全く読み込み ま
せん。
bash は、自分を起動したのがリモートシェルデーモン (通常は rshd) かどう
かを調べます。 rshd によって実行されていると bash が判断 し た 場 合 、
~/.bashrc が存在し、かつ読み込み可能であれば、 bash はコマンドをこのフ
ァイルから読み込んで実行します。 sh として呼び出された場合には、この 動
作 は 行 いません。 --norc オプションを使えばこの動作を禁止できますし、
--rcfile オプションを使えば他のファイルを読ませるようにもできます。しか
し 一般的には rshd はこれらのオプションを付けてシェルを起動しませんし、
指定もできないようになっています。
シェルが実ユーザ (グループ) ID と異なる実効ユーザ (グループ) ID で起 動
さ れ、かつ -p オプションが与えられていない場合は、起動ファイルは全く読
み込まれず、シェル関数は環境から継承されず、 SHELLOPTS が環境変数に含ま
れ て いても無視され、実効ユーザ ID には実ユーザ ID が設定されます。 -p
オプションが起動時に与えられた場合、起動時の動作は同じですが、実効ユ ー
ザ ID は再設定されません。
定義
このドキュメントの残りの部分では、以下の定義を使用します。
ブランク (blank)
空白文字またはタブ文字
単語 (word)
シェルが 1 単位とみなす文字並び。 トークン(token) とも言われます
。
名前 (name)
英数字とアンダースコア文字だけから構成され、かつ最初の文字が英字
かアンダースコア文字である 単語。 識別子 (identifier) とも言われ
ます。
メタ文字 (metacharacter)
クォートされていない場合に、単語区切りとなる文字。以下の文字のう
ちのいずれかです:
| & ; ( ) < > スペース タブ
制御演算子
制御機能を持つトークン。以下のシンボルのうちのいずれかです:
|| & && ; ;; ( ) |
予約語
予約語 (reserved word) とはシェルにとって特別な意味を持つ単語です。以下
の単語がクォートされておらず、かつ単純なコマンド (simple command) の 先
頭 の単語 (後述の シェルの文法を参照) であるか、 case コマンドや for コ
マンドの 3 番目の単語である場合には、予約語として認識されます:
! case do done elif else esac fi for function if in select then until
while { } time [[ ]]
シェルの文法
単純なコマンド (Simple Commands)
単 純なコマンド (simple command) とは、変数の代入を並べたもの (これは省
略可能です) の後に、ブランク区切りの単語とリダイレクションを記述し、 最
後 に制御演算子を置いたものです。最初の単語は実行するコマンドを指定しま
す。残りの単語は起動されるコマンドに引き数として渡されます。
単純なコマンドの返り値はコマンドの終了コードですが、シグナル n を受けて
コマンドが終了した場合には 128+n となります。
パイプライン (Pipeline)
パイプライン (pipeline)は、記号 | で区切った 1 つ以上のコマンド列です。
パイプラインのフォーマットを以下に示します:
[time [-p]] [ ! ] command [ | command2 ... ]
command の標準出力は command2 の標準入力に接続されます。この接続は、 コ
マンドで指定したどのリダイレクションよりも先に実行されます (後述の リダ
イレクションを参照)。
パイプラインの前に、予約語である ! がある場合、そのパイプラインの終 了
ステータスは最後のコマンドの終了ステータスの論理値の NOT を取ったものに
なります。それ以外の場合には、パイプラインのステータスは最後のコマン ド
の 終了ステータスになります。値を返す前に、シェルはパイプライン中の全て
のコマンドが終了するのを待ちます。
パイプラインの前に予約語 time がある場合、コマンドの実行にかかった経 過
時間・ユーザ時間・システム時間がパイプラインの終了時に報告されます。 -p
オプションを指定すると、出力フォーマットが POSIX 仕様に変わります。変数
TIMEFORMAT には、経過時間情報の表示の仕方を指定するフォーマット文字列を
設定できます (後述の シェル変数の項の TIMEFORMAT に関する説明を参照)。
パイプライン中の各コマンドは、それぞれ別のプロセスとして (つまりサブ シ
ェル内で) 実行されます。
リスト
リスト (list) とは、1つ以上のパイプラインを演算子 ;, &, &&, ││ のいずれ
かで区切って並べ、最後に ;, &, のいずれか (これは省略可 能 で
す) を置いたものです。
リスト演算子のうち、 && と ││ の優先順位は同じです。これらの次に、 ; と
& が同じ優先順位で続きます。
コマンドが制御演算子 & で終わっている場合、シェルはコマンドをサブシェル
内 でバックグラウンド (background) で実行します。シェルはコマンドが終了
するのを待たずに、返却ステータス 0 を返します。コマンドを ; で区切っ た
場 合には、これらは順番に実行されます。シェルはそれぞれのコマンドが終了
するのを順番に待ちます。返却ステータスは、最後に実行したコマンドの終 了
ステータスになります。
制 御演算子 && は AND リストを示し、 ││ は OR リストを示します。 AND リ
ストは
command1 && command2
という形式であり、 command1 が終了ステータス 0 を返した場合に限り com-
mand2 が実行されます。
OR リストは
command1 ││ command2
という形式であり、 command1 が 0 以外の終了ステータスを返した場合に限り
command2 が実行されます。AND リストと OR リストの返却ステータスは、リス
ト中で最後に実行されたコマンドの終了ステータスです。
複合コマンド(Compound Commands)
複合コマンド (compound command) を以下に示します:
(list) list はサブシェル内で実行されます。シェルの環境に影響を与えるよ
うな変数の代入や組み込みコマンドは、コマンドの終了後に影響を残し
ません。返却ステータスは list の終了ステータスです。
{ list; }
list が単に現在のシェル環境で実行されます。 list の最後は改行文
字かセミコロンでなければなりません。これはグループコマンド(group
command) と呼ばれます。返却ステータスは list の終了ステータスで
す。
((expression))
expression が後述の 算術式評価で説明される規則に従って評価されま
す。式の値が 0 でない場合、返却ステータスは 0 になります。そうで
ない場合、返されるステータスは 1 になります。これは let "expres-
sion" と全く同じものです。
[[ expression ]]
条件式 expression の評価値に従って 0 または 1 を返します。式は後
述の 条件式で説明する、プライマリによって構成されます。単語分 割
とパス名展開は [[ と ]] の間の単語に対しては行われません。チルダ
展開、パラメータと変数の展開、算術式展開、コマンド置換、プロセス
置換、クォート除去は実行されます。
== 演算子と != 演算子が使われたとき、演算子の右の文字列はパター
ンと解釈され、後述のパターンマッチングで説明する規則に従ってマッ
チ ングが行われます。文字列がパターンにマッチすれば返り値は 0 で
あり、マッチしなければ返り値は 1 になります。パターンの任意の 部
分をクォートして、文字列としてマッチさせることもできます。
式は以下の演算子を使って繋げられます。以下に演算子を優先度の順に
示します:
( expression )
expression の値を返します。これを用いて、演算子の通常の優
先度を変更できます。
! expression
expression が偽ならば真になります。
expression1 && expression2
expression1 と expression2 が両方とも真であれば真になりま
す。
expression1 || expression2
expression1 と expression2 のどちらかが真であれば真となり
ます。
expression1 の値だけで条件式全体の返り値が決定できれば、 && 演算子と ||
演算子は expression2 を実行しません。
for name [ in word ] ; do list ; done
in に続く単語のリストが展開され、要素のリストが生成されます。 変
数 name に は、このリストの各要素が順番にセットされ、その度に
list が実行されます。「in word」が省略された場合、 for コマン ド
は、設定されている位置パラメータそれぞれに対して list を一度ずつ
実行します(後述の パラメータを参照)。返却ステータスは実行され た
最後のコマンドの終了ステータスになります。 in に続く要素を展開し
た結果が空となった場合、コマンドは全く実行されず、返却ステータス
0 が返されます。
for (( expr1 ; expr2 ; expr3 )) ; do list ; done
最初に、算術式expr1が、後述の 算術式評価で説明される規則に従って
評価されます。次に、算術式expr2がゼロになるまで繰り返し評価さ れ
ま す。算術式expr2の評価結果がゼロでなければ、その度毎にlistが実
行され、算術式expr3が評価されます。どの算術式も省略された場合 は
、 評価結果が 1 とみなされた場合のように振る舞います。返却ステー
タスは list 中で実行された最後のコマンドの終了ステータスとなりま
すが、算術式のいずれかが無効である場合には不正な値となります。
select name [ in word ] ; do list ; done
in に続く単語のリストが展開され、要素のリストが生成されます。展
開された単語の集合が番号付きで標準エラー出力に出力されます。「in
word 」が省略された場合、位置パラメータが出力されます (後述の パ
ラメータを参照)。続いて PS3 が表示され、標準入力から 1 行の読 み
込みが行われます。表示された単語のいずれかに対応する数字がこの行
に含まれていれば、 name の値としてその単語が設定されます。行が空
で あれば、単語とプロンプトが再び表示されます。 EOF を読み込むと
コマンドが終了します。これ以外の値の場合には、 name には空文字列
が 設定されます。読み込んだ行は変数 REPLY に格納されます。 break
または return コマンドが実行されるまで、選択を行うたびに list が
実行されます。 select の終了ステータスは、 list 中で最後に実行し
たコマンドの終了ステータスですが、コマンドが全く実行されなかった
場合には 0 となります。
case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
case コマンドは最初に word を展開し、それぞれの pattern に対して
順にマッチングを試みます。マッチングの際にはパス名展開 (後述の
パス名展開を参照) と同じ規則が用いられます。マッチするものが見つ
かると、これに対応する list が実行されます。マッチするものが見つ
かったら、それ以降のマッチングは行われません。マッチするパターン
が無ければ、終了ステータスは 0 になります。マッチするものがあ っ
たら、終了ステータスは list 中で最後に実行されたコマンドの終了ス
テータスになります。
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
最初に if list が実行されます。この終了ステータスが 0 な ら ば
、then list が実行されます。そうでなければ elif list がそれぞれ
順番に実行され、この終了ステータスが 0 ならば、対 応 す る then
list が実行され、コマンドが終了します。そうでなければ、else list
が (もし存在すれば) 実行されます。終了ステータスは最後に実行され
たコマンドの終了ステータスですが、真と評価された条件が全く無い場
合には 0 となります。
while list; do list; done
until list; do list; done
while コマンドは、list 中の最後のコマンドが終了ステータス 0 を返
す まで、繰り返して do list を実行します。until コマンドは while
コマンドとほぼ同じですが、評価の条件が否定となる点が異なります。
do list は、 list 中の最後のコマンドが 0 以外の終了ステータスを
返す限りずっと実行されます。 while コマンドと until コマンドの終
了 ステータスは、 do list で実行された最後のコマンドの終了ステー
タスになりますが、コマンドが全く実行されなかった場合には 0 に な
ります。
[ function ] name () { list; }
name という名前の関数を定義します。関数の本体(body)は、 { と }
で囲まれたコマンドの リストです。単純なコマンドの名前として name
が指定されると、必ずこのリストが実行されます。関数の終了ステータ
スは、関数本体で最後に実行されたコマンドの終了ステータスです (後
述の 関数を参照)。
コメント (COMMENTS)
シ ェルが対話的でない場合、または対話的なシェルにおいて組み込みコマンド
の shopt に対する interactive_comments オプションが有効となっている (後
述 の シェルの組み込みコマンドを参照すること) 場合には、 # で始まる単語
があると、その単語とその行の残りの文字が全て無視されます。対話シェル で
は 、 interactive_comments オプションが有効でなければコメントは使えませ
ん。対話シェルでは、 interactive_comments オプションはデフォルトで有 効
になっています。
クォート
クォート (quoting) を使うと、特定の文字や単語のシェルに対する特別な意味
を取り除けます。クォートを用いると、特殊文字の特殊な扱いを無効にする こ
と や、予約語が予約語として識別されることを防いだり、パラメータの展開を
防げます。
前述の 定義で挙げたメタ文字 (metacharacters) にはそれぞれ特殊な意味があ
るので、その文字自身を表すためにはクォートしなければなりません。
コ マンド履歴展開機能が使われている場合、履歴の展開を防ぐためには、履歴
展開 (history expansion) 文字 (普通 !) をクォートしなければなりませ ん
。
クォートの方法には、 エスケープ文字(escape character), シングルクォート
、ダブルクォートの 3 種類があります。
クォートされていないバックスラッシュ (\) は エスケープ文字です。エス ケ
ー プ文字は という例外を除き、後に続く文字 1 つの文字としての
値を保持させます。 \ という組合せが現われ、かつバックスラッ シ
ュ 自身がクォートされていない場合には、 \ は行を継続することを
表します (つまり、入力ストリームから改行文字が削除され、実質的に無視 さ
れます)。
シ ングルクォートで文字を囲むと、クォート内部のそれぞれの文字は文字とし
ての値を保持します。シングルクォートの間にシングルクォートを置くこと は
できません。これはバックスラッシュを前に付けても同じです。
ダ ブルクォートで文字を囲むとクォート内部の全ての文字は文字としての値を
保持しますが、 $, ‘, \ は例外となります。 $ と ‘ はダブルクォートの内部
で も特殊な意味を失いません。バックスラッシュの場合は、次の文字が $, ‘,
", \, のいずれかである場合に限り特殊な意味を失いません。前 に
バ ックスラッシュを付ければ、ダブルクォート文字をダブルクォートによるク
ォートの内部でクォートできます。
特殊なパラメータである * と @ は、ダブルクォート内部でも特殊な意味を 失
いません (後述の パラメータを参照)。
$’string’ の形式を持つ単語は特殊な扱いを受けます。この単語は string に
展開され、それから ANSI C 標準で仕様が決められている、バックスラッシ ュ
で エスケープされている文字に置き換えられます。バックスラッシュエスケー
プシーケンスは、 (もし存在すれば) 以下のようにデコードされます:
\a 警告 (ベル)
\b バックスペース
\e エスケープ文字
\f フォームフィード文字
\n 改行文字
\r 復帰文字
\t 水平タブ文字
\v 垂直タブ文字
\\ バックスラッシュ
\’ シングルクォート
\nnn ASCII コードの 8 進値が nnn である文字 (1 文字につき数 字
3 桁)。
\xnnn ASCII コードの 16 進値が nnn である文字 (1 文字につき数字
3 桁)。
展開された結果はシングルクォートされているのと同じ状態で、ドル記号は 存
在しなかったかのように扱われます。
ダブルクォートされた文字列の前にドル記号($)があると、文字列は現在のロケ
ールに従って変換されます。現在のロケールが C または POSIX ならば、ド ル
記 号は無視されます。文字列が変換されたり置換された場合には、その結果は
ダブルクォートされているのと同じ状態になります。
パラメータ
パラメータ (parameter) は値を保持するためのものです。パラメータは 名 前
、数字、後述の 特殊なパラメータで挙げる特殊文字のいずれかで表現されます
。シェルでの用法においては、 変数(variable) とは 名前で表現されたパラメ
ータです。
パラメータに値が代入されていれば、そのパラメータは設定 (set) されている
と言われます。空文字列も有効な値です。一度値を設定すると、組み込みコ マ
ンドの unset を使わなければ設定を取り消す (unset する) ことはできません
(後述の シェルの組み込みコマンドを参照)。
変数には、以下の構文で代入できます:
name=[value]
value が与えられなかった場合、変数には空文字列が代入されます。 全 て の
value に対して、チルダ展開、パラメータと変数の展開、コマンド置換、算術
式展開、クォート除去が行われます (後述の 展開を参照)。変数の 整数属性が
設定されている場合 (後述の シェルの組み込みコマンドを参照)、$((...)) の
展開を使っていなくても value に対しての算術展開が行われます (後述の 算
術 式展開を参照)。 特殊パラメータで後述する "$@" という例外を除いて、単
語の分割は行われません。パス名展開も実行されません。
位置パラメータ(Positional Parameters)
位置パラメータ (positional parameter) は、1 桁以上の数値で表されるパ ラ
メータです。ただし 0 は含みません。位置パラメータは、シェルが起動された
ときにシェルの引き数が代入されますが、組み込みコマンドの set を使って代
入 し直すこともできます。代入文を使って位置パラメータへの代入を行うこと
はできません。シェル関数が実行されると、位置パラメータは一時的に置き 換
えられます (後述の 関数を参照)。
2 桁以上の数値を含む位置パラメータを展開するときには、ブレース ({}) で
囲まなければなりません (後述の 展開を参照)。
特殊パラメータ
シェルはいくつかのパラメータを特別扱いします。このようなパラメータは 参
照されるだけであり、値を代入することは許されません。
* (1 から始まる) 全ての位置パラメータに展開されます。ダブルクォー
トの内部で展開が行われたときは、それぞれのパラメータを特別な変数
である IFS の最初の文字で区切って並べた 1 つの単語に展開されます
。つまり、 "$*" は "$1c$2c..." と同じです。ここで c は変 数 IFS
の 値の最初の文字です。 IFS が設定されていなければ、パラメータは
空白で区切られます。 IFS が空文字列の場合、パラメータの間には 区
切り文字は入らず、全てのパラメータは繋げられます。
@ (1 から始まる) 全ての位置パラメータに展開されます。ダブルクォー
トの内部で展開が行われたときは、それぞれのパラメータは別々の単語
に 展開されます。つまり "$@" は "$1" "$2" ... と同じです。位置パ
ラメータが無い場合には、"$@" と $@ を展開しても空文字列になり ま
す (つまり取り除かれます)。
# 位置パラメータの個数を示す 10 進値に展開されます。
? 最後に実行されたフォアグラウンドのパイプラインの終了ステータスに
展開されます。
- 現在のオプションフラグに展開されます。これは起動の時に指定したり
、組み込みコマンド set で設定したり、( -i オプション等で) シェル
自身が設定したりします。
$ シェルのプロセス ID に展開されます。 () を使ったサブシェルの内部
では、$ はサブシェルではなく、現在のシェルのプロセス ID に展開さ
れます。
! 最後に実行されたバックグラウンド (非同期) コマンドのプロセス ID
に展開されます。
0 シェルまたはシェルスクリプトの名前に展開されます。これはシェルの
初期化時に設定されます。コマンドを記述したファイルを 指 定 し て
bash を起動した場合、 $0 にはそのファイルの名前が設定されます。
-c オプションを付けて bash を起動した場合、実行する文字列の後 に
引き数があれば、その最初の値が $0 に設定されます。このオプション
を指定していない場合には、 bash を起動する時に使用した名前が引き
数 0 として与えられ $0 に設定されます。
_ シェルの起動時には、引き数リストで渡された、実行するシェルまたは
シェルスクリプトの絶対ファイル名が設定されます。その後は、前のコ
マンドに対する最後の引き数 (展開後のもの) に展開されます。また、
実行する各コマンドの完全なファイル名が設定され、そのコマンドの環
境にエクスポートされます。メールをチェックするときには、このパラ
メータは現在チェックしているメールのファイル名を保持します。
シェル変数
以下の変数はシェルが設定します:
PPID そのシェルの親のプロセス ID。この変数は読み込み専用です。
PWD cd コマンドで設定された現在の作業ディレクトリ。
OLDPWD cd コマンドで設定された、1 つ前の作業ディレクトリ。
REPLY 組み込みコマンド read に引き数が与えられなかった時に読み込まれた
行が設定されます。
UID 現在のユーザのユーザ ID に展開されます。初期化はシェルの起動時に
行われます。この変数は読み込み専用です。
EUID 現在のユーザの実効ユーザ ID に展開されます。初期化はシェルの起動
時に行われます。この変数は読み込み専用です。
GROUPS 現在のユーザがメンバになっているグループのリストを含んだ配列変数
です。 GROUPS への代入は効果がなく、エラーステータスを返します。
GROUPS が unset された場合はこの変数の特殊な性質はなくなります。
その後に再設定されたとしても元に戻りません。
BASH 現在実行している bash を起動したときに使われた、完全なファイル名
に展開されます。
BASH_VERSION
現在実行している bash のバージョンを示す文字列に展開されます。
BASH_VERSINFO
読 み込み専用の配列変数で、配列の各要素は現在実行されている bash
のバージョン情報を持っています。配列変数の要素に代入される内容を
以下に示します:
BASH_VERSINFO[0] メジャーバージョン番号 (リリース)。
BASH_VERSINFO[1] マイナーバージョン番号 (バージョン)。
BASH_VERSINFO[2] パッチレベル。
BASH_VERSINFO[3] ビルドバージョン。
BASH_VERSINFO[4] リリースステータス (beta1 など)。
BASH_VERSINFO[5] MACHTYPE の値。
SHLVL bash の実体が起動されるたびに 1 ずつ増えます。
RANDOM このパラメータが参照される度に、 0 から 32767 までのランダムな整
数が生成されます。 RANDOM に値を代入すると、乱数の列を初期化でき
ま す。 RANDOM を unset すると、この変数の特殊な性質は無くなりま
す。後で再び set しても元には戻りません。
SECONDS
このパラメータを参照すると、シェルが起動されてからの秒数が返され
ま す。 SECONDS に値を代入した場合、それ以降の参照において返され
る値は、代入された値と代入以降の秒数を足した値になります。 SEC-
ONDS を unset すると、この変数の特殊な性質は無くなります。後で再
び set しても元には戻りません。
LINENO この変数が参照されると、シェルはスクリプトや関数における現在の行
番 号 (1から始まります) を表す 10 進値を代入します。スクリプトや
関数の内部でない場合には、意味のある値が代入されることは保証され
ま せん。 LINENO を unset すると、この変数の特殊な性質は無くなり
ます。後で再び set しても元には戻りません。
HISTCMD
現在のコマンドの履歴番号 (履歴リストにおけるインデックス) です。
HISTCMD を unset すると、この変数の特殊な性質は無くなります。後
で再び set しても元には戻りません。
FUNCNAME
現在実行中のシェル関数の名前です。この変数はシェル関数を実行して
いる間のみ存在します。 FUNCNAME への代入は効果がなく、エラーステ
ータスを返します。 FUNCNAME を unset すると、この変数の特殊な 性
質は無くなります。後で再び set しても元には戻りません。
DIRSTACK
現 在のディレクトリスタックの内容を持つ配列変数 (後述の 配列を参
照) です。組み込みコマンド dirs を使うと、スタック中のディレクト
リがスタック順に表示されます。配列変数の要素に代入を行うと、既に
スタックに入っているディレクトリを変更できますが、ディレクトリの
追 加と削除を行うためには、組み込みコマンドの pushd と popd を使
わなければなりません。この変数に代入を行っても現在の作業ディレク
ト リは変わりません。 DIRSTACK を unset すると、この変数の特殊な
性質は無くなります。後で再び set しても元には戻りません。
PIPESTATUS
フォアグラウンドのパイプラインで最後に実行されたプロセスの終了ス
テータスのリストを含む配列変数です (後述の 配列を参照)。
OPTARG 組み込みコマンド getopts で処理した最後のオプション引き数の値で
す (後述の シェルの組み込みコマンドを参照)。
OPTIND 組み込みコマンド getopts で次に処理されるオプション引き数のイ ン
デックスです (後述の シェルの組み込みコマンドを参照)。
HOSTNAME
現在のホスト名が自動的に設定されます。
HOSTTYPE
bash を実行するマシンの種類をユニークに記述する文字列が自動的に
設定されます。デフォルト値はシステム依存です。
OSTYPE bash を実行するオペレーティングシステムを記述する文字列が自動 的
に設定されます。デフォルト値はシステム依存です。
MACHTYPE
bash を実行するシステムの種類を完全に指定する文字列が、 GNU 標準
の cpu-company-system の形式で設定されます。デフォルト値はシステ
ム依存です。
SHELLOPTS
コロン区切りのリストで、有効になっているシェルのオプションを示し
ます。リスト中のそれぞれの単語は、組み込みコマンド set の -o オ
プ ション (後述の シェルの組み込みコマンドを参照) に対する有効な
引き数になっています。 SHELLOPTS に入っているオプション は 、set
-o を実行した場合にも on であると報告されます。この変数が bash
の起動時に環境変数に入っていた場合、どの起動ファイルを読むよりも
前にリスト中のシェルオプションが有効になります。この変数は読み込
み専用です。
COMP_WORDS
現在のコマンドラインの各単語からなる配列変数 (後述の 配列 参 照)
で す 。この変数はプログラム補完機能 (後述の プログラム補完 を参
照) から呼ばれたシェル関数においてのみ有効です。
COMP_CWORD
現在カーソル位置が置かれている単語の ${COMP_WORDS} におけるイ ン
デ ックスです。この変数はプログラム補完機能 (後述の プログラム補
完 を参照) から呼ばれたシェル関数においてのみ有効です。
COMP_LINE
現在のコマンドラインです。この変数はプログラム補完機能 (後 述 の
プ ログラム補完 を参照) から呼ばれたシェル関数においてのみ有効で
す。
COMP_POINT
現在のコマンドの先頭からの相対値として与えられたカーソル位置のイ
ンデックスです。現在のカーソル位置が現在の現在のコマンドの最後に
ある場合、この変数の値は ${#COMP_LINE} と等しくなります。この 変
数はプログラム補完機能 (後述の プログラム補完 を参照) から呼ばれ
たシェル関数においてのみ有効です。
以下の変数はシェルが使用します。場合によっては、 bash がデフォルト値 を
変数に代入します。このような場合については後述します。
IFS 内部フィールド区切り文字 (Internal Field Separator) です。展開を
行った後に単語を分割する場合や、組み込みコマンドの read を使った
時に行を単語に分割する場合に使われます。デフォルト値は ‘‘<空白><
タブ><改行>’’ です。
PATH コマンドの検索パスです。シェルがコマンドを検索するディレクトリを
コロンで区切って並べたリストです (後述の コマンドの実行を参照)。
デフォルトのパスはシステム依存で、 bash をインストールしたシステ
ム 管 理 者 が 設 定 し ま す 。 一 般 的 な 値 は
‘‘/usr/gnu/bin:/usr/local/bin:/usr/ucb:/bin:/usr/bin:.’’ です。
HOME 現在のユーザのホームディレクトリです。組み込みコマンド cd のデフ
ォルトの引き数になります。この変数の値は、チルダ展開を実行すると
きにも使われます。
CDPATH cd コマンドの検索パスです。これは、 cd コマンドで指定した対象デ
ィレクトリを探すディレクトリをコロンで区切って並べたリストです。
例えば、‘‘.:~:/usr’’ といった値になります。
BASH_ENV
bash がシェルスクリプトを実行する時にこの値が設定されている場合
、この値は (~/.bashrc のように) シェルを初期化するコマンドが書か
れているファイル名と解釈されます。 BASH_ENV の値をファイル名とし
て処理する前には、パラメータ展開、コマンド置換、算術的展開が行わ
れます。この結果のファイルを検索する際には PATH は使用されません
。
MAIL このパラメータにファイル名が設定されており、かつ変数 MAILPATH が
設定されていなければ、 bash は指定されたファイルへのメールの到着
をユーザに通知します。
MAILCHECK
bash がメールをチェックする頻度を (秒数で) 指定します。デフォ ル
ト値は 60 秒です。メールをチェックする時間になると、シェルはプラ
イマリのプロンプトを表示する前にチェックを行います。この変 数 が
unset された場合、あるいはこの変数に 0 より大きい数値以外が代入
された場合は、シェルはメールのチェックを行いません。
MAILPATH
メールのチェックに使うファイル名をコロンで区切って並べたリストで
す。特定のファイルにメールが到着したときに出力されるメッセージは
、‘?’ を使ってファイル名をメッセージから区切ることによって指定で
きます。メッセージのテキスト中で使われたときは、 $_ は現在のメー
ルファイルの名前に展開されます。設定例:
MAILPATH=’/var/mail/bfox?"You have mail":~/shell-mail?"$_ has
mail!"’
この変数のデフォルト値は bash が与えますが、 bash が使うユーザの
メールファイルの位置はシステム依存です (/var/mail/$USER 等)。
PS1 このパラメータの値は展開されてプライマリのプロンプト文字列として
使われます。 (後述の プロンプトを参照)、デフォルト値は ‘‘\s-\v\$
’’ です。
PS2 このパラメータの値は PS1 と同じように展開され、セカンダリのプ ロ
ンプト文字列として使われます。デフォルト値は ‘‘> ’’ です。
PS3 このパラメータの値は select コマンド (前述の シェルの文法を参照)
のプロンプトとして使われます。
PS4 このパラメータは PS1 と同じように展開されます。この値は実行ト レ
ース中に bash が表示する各コマンド前に出力されます。複数段の間接
レベル (levels of indirection) を示すときは、 PS4 の最初の文字が
必要に応じて複数回表示されます。デフォルト値は ‘‘+ ’’ です。
TIMEFORMAT
このパラメータの値は、予約語である time が先頭に付いているパイプ
ラインに対して、時間情報の表示の仕方を指定するフォーマット文字列
と して使われます。 % は、時間の値などに展開されるエスケープシー
ケンスを示すための文字です。エスケープシーケンスとその意味を以下
に示します。ただし、ブレース ([]) は省略可能であることを表します
。
%% % 文字そのもの。
%[p][l]R 経過した秒数。
%[p][l]U ユーザモードで使われた CPU の秒数。
%[p][l]S システムモードで使われた CPU の秒数。
%P CPU のパーセンテージ。(%U + %S) / %R で算出されます。
p 省略可能で、精度 (precision) が何桁であるかを指定します。つ ま
り 小数点以下の桁数を指定します。この値が 0 ならば、小数点や小数
の部分は出力されません。また、小数点以下で指定できるのは 3 桁 ま
で で す。つまり、p の値が 3 より大きければ 3 に変更されます。 p
を指定しなければ、この値は 3 となります。
l は省略可能ですが、指定すると、分を含み、 MMmSS.FF という形式の
長 いフォーマットになります。小数を含むかどうかは p の値によって
決まります。
こ の 変 数 が 設 定 さ れ て い な け れ ば 、 bash は
$’\nreal\t%3lR\nuser\t%3lU\nsys%3lS’ という値が指定されているか
のように動作します。この値が空文字列ならば、時間の情報は表示され
ません。フォーマット文字列の表示の際には、末尾に改行文字が追加さ
れます。
HISTSIZE
コマンド履歴に記憶するコマンドの数 (後述の HISTORY を参照)。
HISTFILE
コマンド履歴が保存されるファイルの名前 (後述の 履歴を参照)。デフ
ォ ルト値は ~/.bash_history です。設定されていない場合、対話シェ
ルが終了する時に履歴の保存が行われません。
HISTFILESIZE
履歴ファイルに保持する履歴の最大数です。この変数に値が代入された
場合、その行数を越えないように、必要に応じて履歴ファイルが切り詰
められます。デフォルト値は 500 です。対話シェルが終了する時に も
、履歴ファイルのサイズはファイル書き込みの後にこのサイズに切り詰
められます。
OPTERR 値として 1 が設定されている場合、 bash は組 み 込 み コ マ ン ド
getopts (後述の シェルの組み込みコマンドを参照) を使って生成した
エラーメッセージを表示します。シェルが起動されたり、シェルスクリ
プトが実行される度に、 OPTERR は 1 に初期化されます。
LANG LC_ で始まる変数で特に選択されない任意のカテゴリに対して、ロケー
ルのカテゴリを決めるために使います。
LC_ALL この変数はロケールのカテゴリを指定する LC_ 変数と LANG の値を 全
て上書きします。
LC_COLLATE
この変数はパス名展開の結果をソートするときに使用される照合順序と
、パス名展開とパターンマッチングにおける範囲展開、同値クラス、照
合シーケンスの動作決定します。
LC_CTYPE
この変数は、パス名展開とパターンマッチングにおける文字の解釈と文
字クラスの挙動を決めます。
LC_MESSAGES
この変数は、$ の後に続くダブルクォートされた文字列の翻訳に使うロ
ケールを決めます。
LC_NUMERIC
この変数は数字のフォーマットに使用するロケールカテゴリを決定しま
す。
LINES 組み込みコマンド select によって、選択されたリストを表示する際の
行数の決定に用いられます。 SIGWINCH を受信すると自動的に設定され
ます。
COLUMNS
組み込みコマンド select によって、選択されたリストを表示する際の
端末幅の決定に用いられます。 SIGWINCH を受信すると自動的に設定さ
れます。 PROMPT_COMMAND 設定されていると、プライマリプロンプトを
出す前に毎回、この値がコマンドとして実行されます。
IGNOREEOF
単 独で入力された EOF 文字を受け取ったときの対話シェルの動作を制
御します。この変数が設定されていれば、指定されている値の数だけの
EOF 文字を連続して行頭の文字として入力しなければ bash は終了しま
せん。この変数に数値以外の値が設定されている場合や、値が設定され
ていない場合には、デフォルト値として 10 が使われます。この変数が
存在しなければ、 EOF 文字はシェルへの入力の終わりを示します。
TMOUT 0 より大きい値が設定されていると、この値はプライマリプロンプトを
出した後に入力を待つ秒数として解釈されます。この秒数だけ待った時
点で入力が無ければ bash は終了します。
FCEDIT 組み込みコマンド fc が使うデフォルトのエディタです。
FIGNORE
ファイル名補完 (後述の READLINE を参照) を行う際に無視するサフィ
ッ クスをコロンで区切って並べたリストです。 FIGNORE のエントリの
いずれかにサフィックスがマッチするファイル名は、ファイル名補完に
マ ッ チ す る フ ァイルのリストから除外されます。例えば値として
‘‘.o:~’’ を設定します。
GLOBIGNORE
パス名展開で無視するファイル名の集合を定義するパターンをコロンで
区切って並べたリストです。パス名展開パターンにマッチするファイル
名が GLOBIGNORE 内のパターンのどれかにもマッチする場合、これはマ
ッチしたもののリストから削除されます。
INPUTRC
readline の 起動ファイルのファイル名です。これはデフォルト値の
~/.inputrc (後述の READLINE を参照) を上書きします。
HISTCONTROL
ignorespace の値が設定されていると、 空白文字で始まる行は履歴 リ
ストに入りません。 ignoredups の値が設定されていると、履歴の最後
の行にマッチする行は履歴リストに入りません。 ignoreboth の値はこ
れ らの 2 つのオプションを同時に実現します。設定されていないか上
記のいずれの値でもない場合には、パーザが読み込んだ全 て の 行 は
HISTIGNORE の値が示す条件の下で履歴リストに保存されます。この変
数は既に古くなっており、この機能は HISTIGNORE 変数で用いることに
な っています。複数行にまたがる複雑なコマンドの場合は 2 番目以降
の行が調べられることはありません。よって、これら は HISTCONTROL
の値に関わらず履歴に追加されます。
HISTIGNORE
どのコマンド行を履歴リストに保存するかを決めるために使うパターン
をコロンで区切って並べたリストです。それぞれのパターンは行の先頭
と比較され、行全体が完全に一致しなければなりません (‘*’ が暗黙的
に追加されることはありません)。各パターンの評価は HISTCONTROL で
指定したチェックが行われた後の行に対して実行されます。通常のシェ
ルのパターンマッチング文字以外に、 ‘&’ が履歴の前の行にマッチ し
ま す。バックスラッシュを使って ‘&’ をエスケープできます。マッチ
ングを試みる前にバックスラッシュは取り除かれます。複数行にまたが
る複雑なコマンドの場合、2 番目以降の行は調べられません。よって、
これらは HISTIGNORE の値に関わらず履歴に追加されます。
histchars
2 文字または 3 文字で、履歴の展開とトークン分割 (後述の 履歴展開
を 参照) を制御します。最初の文字は 履歴展開 (history expansion)
文字であり、履歴展開の先頭を示す文字です。通常、これは ‘!’ で す
。 2 番目の文字は 簡易置換 (quick substitution) 文字であり、前に
入力したコマンドの文字列を別の文字列に置き換えて再実行を行うため
の省略表現として使います。デフォルト値は ‘^’ です。 3 番目の文字
は省略可能です。単語の先頭でこの文字が見つかると、行の残りの部分
が コメントとなるような文字を指定します。これは通常は ‘#’ です。
履歴コメント文字があると、その行の残りの単語に対する履歴置換はス
キップされます。この文字があるからといって、必ずしもシェルのパー
ザが行の残りの部分をコメントとして扱うわけではありません。
HOSTFILE
/etc/hosts と同じフォーマットであり、シェルがホスト名を補完す る
必要があるときに読み込むファイルの名前を示します。シェルの実行中
でも補完するホスト名のリストを変更できます。この変数が変更された
次の機会にホスト名の補完を試みるとき、 bash は新しいファイルの内
容を既存のデータベースに追加します。 HOSTFILE が設定されているが
その値が空文字列の場合、 bash は補完可能なホスト名のリストを取得
するために /etc/hosts を使用します。 HOSTFILE が unset された 場
合は、ホスト名のリストはクリアされます。
auto_resume
この変数はシェルがユーザとジョブ制御の相互作用をどのように扱うか
を決めます。この変数を設定した場合、1 語からなるリダイレクト無し
の単純なコマンドが、停止中ジョブの実行再開候補として扱われます。
曖昧な指定は許されません。入力された文字列で始まるジョブが複数あ
る 場合には、最後にアクセスされたものが選ばれます。ここでの 名前
とは、コマンドを起動する際に使ったコマンドラインのことです。この
値 に exact が設定されている場合、与えられた文字列は停止している
ジョブの名前に正確にマッチしなければなりません。 substring が 設
定されている場合は、与えられた文字列は停止しているジョブの名前の
部分文字列にマッチする必要があります。 substring という値は、 ジ
ョブ識別子の %? に似た機能を持っています (後述の ジョブ制御を参
照)。これ以外の値が設定されている場合、与えられた文字列は停止 し
ているジョブの名前のプレフィックスでなければなりません。これはジ
ョブ識別子の % と似た機能を持っています。
COMPREPLY
bash が可能な補完候補を読み込む配列変数です。この値はプログラ ム
補完機能 (後述の プログラム補完 を参照) によって呼び出されたシェ
ル関数によって生成されます。
配列
bash は 1 次元の配列変数を扱うことができます。全ての変数は配列として 使
用できます。 declare 組み込みコマンドを使えば、明示的に配列を宣言できま
す。配列のサイズの上限はありませんし、メンバのインデックス付けや代入 を
連 続的にしなければならないという条件もありません。配列のインデックス付
けは 0 から始まる整数を用いて行います。
変数の代入の際に name[subscript]=value という記法が使われた場合、配列は
自動的に生成されます。 subscript は算術式として扱われますが、この式は評
価すると 0 以上の数値になるものでなければなりません。明示的に配列を宣言
す るには、 declare -a name を使います (後述の シェルの組み込みコマンド
を参照)。 declare -a name[subscript] も許されます。subscript は無視され
ます。組み込みコマンドの declare と readonly を使うと、配列変数に対して
属性を設定できます。どちらの属性も配列のメンバ全てに対して適用されま す
。
配 列 の 代入は name=(value1 ... valuen) という形式の複合代入 (compound
assignment) を用いて行います。ここでそれぞれの value の 形 式 は [sub-
script]=string です。必要なのは string だけです。ブラケット([])と添字を
省略しなかった場合、そのインデックスに対して代入が行われます。省略し た
場 合には、代入される要素のインデックスは、その文の中で直前に代入された
インデックスに 1 を加えたものになります。インデックスは 0 から始まり ま
す。この記法は組み込みコマンド declare でも使えます。個別の配列要素に対
する代入は、先に説明した name[subscript]=value の記法を使って行います。
配列の任意の要素は、${name[subscript]} を使って参照できます。パス名展開
との衝突を避けるためにブレースが必要です。添字(subscript)が @ か * なら
ば 、その単語は name の全ての要素に展開されます。これらの添字が異なるの
は、単語がダブルクォートの内部にある場合だけです。単語がダブルクォー ト
さ れていれば、${name[*]} は 1 つの単語に展開されます。この単語は、配列
の各メンバの値を特殊変数 IFS の値で区切って並べたものです。${name[@]}は
、 name の各要素を別々の単語に展開します。配列のメンバが全く無いときは
、${name[@]} は空の単語に展開されます。これは特殊パラメータ * や @ に似
て い ま す ( 前 述 の 特殊パラメータを参照)。${#name[subscript]} は
${name[subscript]} の長さに展開されます。 subscript が * または @ の 場
合 は、配列中の要素数に展開されます。添字無しで配列変数を参照すると、要
素 0 を参照したことになります。
組み込みコマンドの unset は配列の破棄に使わ れ ま す 。unset name[sub-
script] とすると、インデックスが subscript である配列の要素が破棄されま
す。 unset name (name は配列) または unset name[subscript] (subscript
が * または @) とすると、配列全体が破棄されます。
組 み込みコマンドの declare, local, readonly いずれにおいても、 -a オプ
ションで配列を指定できます。組み込みコマンド read では、 -a オプショ ン
を 使えば標準入力から読み込んだ単語のリストを配列に代入できます。組み込
みコマンド set と declare では、別の変数への代入に再利用できるような 形
で配列の値を表示します。
展開
展 開はコマンドラインが単語へ分割された後に (コマンドライン上で) 行われ
ます。行われる展開は 7 種類あります: ブレースの展開 (brace expansion),
チ ル ダの展開 (tilde expansion), パラメータと変数の展開 (parameter and
variable expansion), コマンド置換 (command substitution), 算術 式 展 開
(arithmetic expansion), 単 語 の 分割 (word splitting), パス名の展開
(pathname expansion)。
展開の順序は次のようになります: ブレース展開、チルダ展開、パラメータ ・
変数・算術式展開、コマンド置換 (左から右へ)、単語分割、パス名展開。
これらに加えて プロセス置換 (process substitution) をサポートできるシス
テムもあります。
展開した部分の単語の数が変化することがあるのは、ブレース展開、単語の 分
割 、パス名展開だけです。他の展開では、 1 つの単語は 1 つの単語に展開さ
れます。この規則の唯一の例外は先に説明した
"$@" と "${name[@]}" の展開 ( パラメータを参照) だけです。
ブレース展開
ブレース展開 (brace expansion) を使うと、任意の文字列を生成できます。こ
の 機構はパス名展開に似ていますが、生成されたファイル名が実在する必要は
ありません。ブレース展開されるパターンは、 前置部分 (preamble: 省 略 可
能) 、 対 に な るブレースの間にコンマで区切って並べた文字列、 後置部分
(postscript: 省略可能) を順に並べたものです。前置部分はブレース内にある
文 字列それぞれの先頭部分に追加され、後置部分は左から右に順に展開されて
得られたそれぞれの文字列の末尾に追加されます。
ブレースの展開は入れ子にできます。展開して得られた文字列はソートされ ず
、左から右への順番がそのまま残ります。例えば a{d,c,b}e は ‘ade ace abe’
と展開されます。
ブレースの展開は他のどの展開よりも前に実行されます。また、他の展開に お
い て特殊な意味を持つ文字もそのまま結果に残ります。つまり、厳密にテキス
ト操作だけを行います。 bash は、展開の文脈やブレースの間のテキストに 対
して文法的な解釈を適用することは一切ありません。
正 しい形のブレース展開には、クォートされていない開きブレースと閉じブレ
ース、また少なくとも 1 つのクォートされていないコンマが含まれていなけれ
ば なりません。正しい形でないブレース展開は全て、変更されないでそのまま
残ります。 { や , をバックスラッシュでクォートすれば、ブレース展開の 一
部 と解釈されないようにできます。パラメータ展開との衝突を避けるため、文
字列 ${ はブレース展開の対象とは解釈されません。
この仕組みは、生成される文字列の共通先頭部分が上記の例より長い場合に 、
短縮表現としてよく使用されます:
mkdir /usr/local/src/bash/{old,new,dist,bugs}
あるいは
chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
ブ レース展開の導入によって、伝統的な sh とは少し非互換になった部分があ
ります。 sh は単語の一部として開きブレースや閉じブレースが現われても 特
別 扱いはせず、そのまま出力に残します。 bash はブレース展開の結果として
単語からブレースを取り除きます。例えば sh に file{1,2} のように入力され
た 単語はそのままの形で出力されますが、 bash ではこの同じ単語は展開され
て file1 file2 のように出力されます。厳密に sh と互換にした け れ ば 、
bash を +B オプションを付けて起動するか、 set コマンドに +B オプション
を与えてブレース展開を無効にしてください (後述する シェル組み込みコマン
ドを参照)。
チルダ展開
クォートされていないチルダ (‘~’) で単語が始まった場合、クォートされてい
ないスラッシュよりも前にある文字すべて (クォートされていないスラッシ ュ
が 無ければすべての文字) はチルダプレフィックス (tilde-prefix) と解釈さ
れます。クォートされている文字がチルダプレフィックス中に無ければ、チ ル
ダ プレフィックス中のチルダ以降の文字は、ログイン名 (login name) になる
可能性がある文字列として扱われます。このログイン名が空文字列ならば、 チ
ル ダはシェルパラメータ HOME の値に置き換えられます。 HOME が設定されて
いない場合は、代わりにシェルを実行しているユーザのホームディレクトリ に
置 き換えられます。ログイン名が空でなければ、チルダプレフィックスは指定
されたログイン名に対応するホームディレクトリに置き換えられます。
チルダプレフィックスが ‘~+’ ならば、チルダプレフィックスはシェ ル 変 数
PWD の値に置き換えられます。チルダプレフィックスが ‘~-’ ならば、シェル
変数 OLDPWD の値に置き換えられます (値が設定されていれば)。チルダプレフ
ィ ックス中のチルダより後の文字が数値 N であれば (数値の前に ‘+’ や ‘-’
を置くこともできます)、チルダプレフィックスはディレクトリスタック内の対
応 する要素に置換されます。置換される要素は、チルダプレフィックスを引き
数として組み込みコマンド dirs を実行したときに表示されるものです。チ ル
ダ プレフィックスにおけるチルダ以降の文字が、先行する ‘+’ や ‘-’ のない
数値である場合は、‘+’ であるとみなされます。
ログイン名が有効でない場合や、チルダ展開が失敗した場合には、単語は置 き
換えられません。
全 ての変数代入において、 : や = の直後にクォートされていないチルダプレ
フィックスがないかチェックが行われます。もし見つかった場合にはこれら も
チ ルダ展開されます。したがって、 PATH, MAILPATH, CDPATH への代入にチル
ダを含むファイル名を使えば、シェルは展開された値を代入します。
パラメータの展開
‘$’ 文字があると、パラメータ展開、コマンド置換、算術式展開が行われま す
。 展開されるパラメータ名やシンボルは、ブレースで括ることもできます。ブ
レースは省略可能ですが、変数の直後に変数名の一部と解釈できる文字が置 か
れ た場合に、その文字と共に変数が展開されてしまうのを防ぐために用意され
ています。
ブレースを使った場合、マッチングを終えるブレースは最初の ‘}’ です。ただ
し バックスラッシュでエスケープされているものやクォートされている文字列
中のものは含まれませんし、算術式展開やコマンド置換、パラメータ展開に 入
っているものも含まれません。
${parameter}
parameter の値が置換されます。ブレースが必要になるのは、 parame-
ter が 2 桁以上の数字を持つ位置パラメータの場合や、 parameter の
直後の文字を名前の一部として解釈させたくない場合です。
parameter の 最 初 の文字が感嘆符である場合、間接変数レベル (level of
variable indirection) という概念が導入されます。 bash は、展開に param-
eter そのものの値を使用するのでなく、 parameter の感嘆符を除いた残りの
文字を変数名として扱い、その変数の値をその後の展開に使用します。これ が
間接展開 (indirect expansion) と呼ばれるものです。ただし ${!prefix*} の
展開は例外です。これは以下で説明します。
以下に示すそれぞれの場合、word に対してチルダ展開、パラメータ展開、コマ
ン ド置換、算術式展開が行われます。部分文字列展開以外の場合、 bash はパ
ラメータが設定されているか、空ではないかを調べます。コロンを省略した 場
合には設定されているかどうかのみを調べます。
${parameter:-word}
デ フォルトの値を使います。 parameter が設定されていないか空文字
列であれば、 word を展開したものに置換されます。そうでなければ、
parameter の値に置換されます。
${parameter:=word}
デ フォルトの値を代入します。 parameter が設定されていないか空文
字列であれば、 word を展開したものが parameter に代入されます 。
そ れから parameter の値への置換が行われます。位置パラメータや特
殊パラメータへの代入をこのように行うことはできません。
${parameter:?word}
空文字列または設定されていない場合にエラーを表示します。 parame-
ter が 空文字列または設定されていない場合、word を展開したもの
(word がなければパラメータが空文字列または設定されていないことを
示すメッセージ) が標準エラー出力に出力されます。シェルが対話的で
なければ、シェルは終了します。パラメータに空文字列以外が設定され
ていれば、 parameter の値への置換が行われます。
${parameter:+word}
別 の値を使用します。 parameter が空文字列または設定されていなけ
れば、空文字列に置換されます。そうでなければ word を展開したもの
に置換されます。
${parameter:offset}
${parameter:offset:length}
部 分文字列展開。 parameter を展開したものから最大 length 文字を
取り出します。先頭の文字は offset で指定します。length を省略 す
る と、 offset で指定した文字を先頭にして、 parameter の残り全部
が含まれる部分文字列に展開します。 length と offset は算術式です
(後述の 算術式評価を参照)。 length の評価結果は 0 以上の数でなけ
ればなりません。 offset を評価すると 0 未満の数になる場合、こ の
値 は parameter の 値の末尾からのオフセットとして使われます。
parameter が @ ならば、結果は offset から始まる length 個の位 置
パ ラメータになります。 parameter が @ または * のインデックスが
付いている配列名ならば、結果は配列の ${parameter[offset]} を先頭
とする要素 length 個となります。位置パラメータを使う場合以外は、
部分文字列のインデックスは 0 から始まります。位置パラメータの 場
合には、インデックスは 1 から始まります。
${!prefix*}
prefix で始まるすべての変数の名前に展開して、 IFS 特殊変数の最初
の文字によって区切ります。
${#parameter}
parameter の値に含まれる文字数に置換されます。 parameter が * ま
たは @ ならば、位置パラメータの数に置換されます。 parameter が *
または @ が添字になっている配列名ならば、配列中の要素数に置換 さ
れます。
${parameter#word}
${parameter##word}
word が展開され、パス名展開の場合と同じようなパターンを作ります
。このパターンが parameter の値の先頭部分とマッチする場合、展 開
し て 得 ら れ る値は parameter を展開した値から最短一致パターン
(‘‘#’’の場合) または最長一致パターン (‘‘##’’ の場合) を取り除 い
た ものになります。 parameter が @ または * である場合、パターン
を削除する操作は全ての位置パラメータに順番に適用され、展開結果は
リ ストとして得られます。 parameter が @ または * が添字になって
いる配列変数である場合、パターンを削除する操作は配列の全ての要素
に順番に適用され、展開結果はリストとして得られます。
${parameter%word}
${parameter%%word}
word が展開され、パス名展開の場合と同じようなパターンを作ります
。このパターンが parameter を展開した値の末尾の部分とマッチす る
場 合 、 展 開 結果は parameter を展開した値から最短一致パターン
(‘‘%’’ の場合) または最長一致パターン (‘‘%%’’ の場合) を取り除い
た ものになります。 parameter が @ または * である場合、パターン
を削除する操作は全ての位置パラメータに順番に適用され、展開結果は
リ ストとして得られます。 parameter が @ または * が添字になって
いる配列変数である場合、パターンを削除する操作は配列の全ての要素
に順番に適用され、展開結果はリストとして得られます。
${parameter/pattern/string}
${parameter//pattern/string}
pattern が展開され、パス名展開の場合と同じようなパターンを作りま
す。 parameter の展開が行われ、その値のうち pattern に最長一致す
る部分が string に置換されます。前者の形式の場合には、最初にマッ
チした部分だけが置換されます。後者の形式の場合には、マッチした部
分は全て string に置換されます。 pattern が # で始まる場合には、
パターンは parameter を展開した値の先頭にマッチしなければなり ま
せ ん。 pattern が % で始まる場合には、パターンは parameter を展
開した値の末尾にマッチしなければなりません。 string が空の場合に
は pattern に マ ッチした部分は削除されます。またこの場合には
、pattern の後に続く / は省略可能です。 parameter が @ または *
である場合、置換操作は全ての位置パラメータに順番に適用され、展開
結果はリストとして得られます。 parameter が @ または * が添字 に
なっている配列変数である場合、置換操作は配列の全ての要素に順番に
適用され、展開結果はリストとして得られます。
コマンド置換
コマンド置換 (command substitution) を用いると、コマンド名をコマンド の
出力で置き換えできます。コマンド置換には以下の 2 つの形式があります:
$(command)
または
‘command‘
bash による展開は、command の実行およびコマンド置換の部分をコマンドの標
準出力と置換することにより実行されます。この際、末尾の改行文字は削除 さ
れ ます。文字列の途中にある改行文字は削除されませんが、単語分割の際に削
除されることがあります。コマンド置換 $(cat file) は、同じ意味を持ち、し
かも高速な $(< file) に置き換え可能です。
バ ッククォートを使う古い形式の置換を用いたとき、バックスラッシュは文字
通りの意味を保ちますが、 $, ‘, \ の前にある場合は例外となります。バック
ス ラッシュが前置されていないバッククォートがあると、そこでコマンド置換
は閉じられます。 $(command) という形式を用いたときは、括弧の間にある 全
ての文字がコマンドとなります。特別扱いされる文字はありません。
コ マンド置換は入れ子にできます。バッククォート形式の時に入れ子を行うに
は、内側のバッククォートをバックスラッシュでエスケープします。
置換がダブルクォート内部にある場合には、置換の結果に対する単語分割と パ
ス名展開は行われません。
算術式展開
算 術式展開を使うと、算術式を評価して、その結果に置換できます。算術式展
開のフォーマットを次に示します:
$((expression))
expression はダブルクォート内部にある場合と同様に扱われますが、括弧の内
側 のダブルクォートが特別扱いされることはありません。式に含まれる全ての
トークンに対して、パラメータ展開・文字列展開・コマンド置換・クォート の
削除が行われます。算術式置換は入れ子にできます。
評価は後述の 算術式評価で示す規則に基づいて行われます。 expression が不
正であれば、 bash は評価の失敗を示すメッセージを出力し、置換を全く行 い
ません。
プロセス置換
プ ロセス置換 (process substitution) がサポートされるのは、名前付きパイ
プ (FIFO) または名前付きオープンファイルの /dev/fd メソッドをサポートし
て いるシステムです。これは <(list) または >(list) の形になります。プロ
セス list は、その入力や出力が FIFO または /dev/fd 中の何らかのファイル
に 接続された状態で実行されます。このファイルの名前は、展開の結果として
、引き数のかたちで現在のコマンドに渡されます。 >(list) の形式を使った場
合、ファイルへの書き込みは list への入力となります。 <(list) の形式を使
った場合、引き数として渡されたファイルは list の出力を得るために読み 込
まれます。
利 用可能であれば、プロセス置換 (process substitution) は、パラメータ展
開・変数展開・コマンド置換・算術式展開と同時に行われます。
単語の分割
シェルはパラメータ展開・コマンド置換・算術式展開 (ダブルクォートの内 部
ではこれらの展開は行われません) の結果をスキャンし、 単語分割を行います
。シェルは IFS のそれぞれの文字を区切り文字として扱い、他の展開の結果を
これらの文字によって単語に分割します。 IFS が設定されていないか、その値
が正確にデフォルト値の <スペース><タブ><改行> ならば、 IFS 文字の任意の
列で単語が区切られます。 IFS がデフォルト以外の値を持っていれば、空白文
字 (スペースおよび タブ) の列は単語の先頭と末尾では無視されます。これは
空白文字が IFS の値 ( IFS 空白文字) に含まれる限り成り立ちます。 IFS に
含まれ、 IFS 空白文字ではない文字は全て、隣接する任意の IFS 空白文字 と
一緒になってフィールドの区切りとなります。 IFS 空白文字の列も区切り文字
として扱われます。 IFS の値が空文字列であれば、単語分割は全く行われませ
ん。
明 示的に指定した空の引き数("" または ’’)は削除されずに残ります。クォー
トされていない暗黙的な空の引き数が、値を持たないパラメータを展開した 結
果 として得られますが、これらは削除されます。値を持たないパラメータがダ
ブルクォート内部で展開されると、これは空である引き数となり、消されず に
残ります。
展開が行われなければ単語分割も行われない点に注意してください。
パス名展開
-f オプションが指定されていなければ、単語分割を行った後に bash はそれぞ
れの単語が *, ?, [ を含んでいるかどうか調べます。これらの文字のいずれか
が見つかると、その単語は パターンと見なされ、パターンにマッチするファイ
ル名をアルファベット順にソートしたリストに置換されます。マッチするフ ァ
イ ル名が見つからず、かつシェルのオプション nullglob が無効ならば、その
単語は変更されずにそのまま残ります。 nullglob オプションが設定されて い
て 、かつマッチするファイル名が見つからなければ、その単語は削除されます
。シェルのオプション nocaseglob が有効ならば、マッチングにおいてアル フ
ァ ベットの大文字と小文字は区別されません。パターンをパス名展開に使うと
き、名前の先頭やスラッシュの直後の ‘‘.’’ は明示的にマッチさせなけれ ば
なりません。ただしシェルのオプション dotglob が設定されている場合は例外
です。パス名のマッチングを行うとき、スラッシュ文字は必ず明示的にマッ チ
さ せなければなりません。これ以外の場合には、 ‘‘.’’ が特別扱いされるこ
とはありません。シェルのオプション nocaseglob, nullglob, dotglob の詳し
い 説 明については、後述の シェルの組み込みコマンドに書かれている shopt
の説明を参照してください。
シェル変数 GLOBIGNORE を使って、 パターンにマッチするファイル名の集合を
制 限できます。 GLOBIGNORE が設定されていれば、マッチするファイル名のう
ち GLOBIGNORE 中のパターンにもマッチしたものは、マッチしたもののリス ト
から取り除かれます。ファイル名 ‘‘.’’ と ‘‘..’’ は必ず無視されます。こ
れは GLOBIGNORE が設定されていても同じです。しかし、 GLOBIGNORE を設 定
するとシェルオプションの dotglob が有効になるので、 ‘‘.’’ で始まる他の
ファイル名は全てマッチします。 ‘‘.’’ で始めるファイル名を無視する古 い
動 作 をさせるには、 ‘‘.*’’ を GLOBIGNORE のパターンに含めてください。
GLOBIGNORE が設定されていなければ、 dotglob オプションは無効になりま す
。
パターンマッチング
パ ターンに含まれる文字のうち、後述する特殊パターン文字以外の文字は、自
分自身にマッチします。NUL 文字がパターン中に現われてはいけません。特 殊
パ ターン文字をその文字そのものにマッチさせるためには、クォートしなけれ
ばなりません。
特殊パターン文字は以下の意味を持っています:
* 空文字列を含む、任意の文字列にマッチします。
? 任意の 1 文字にマッチします。
[...] 括られた文字のうち任意の 1 文字にマッチします。 2 つの文字の間に
ハイフンを入れたものは、 範囲表現 (range expresion) を表します。
ソート順で 2 つの文字の間にある任意の文字と、両端の 2 文字がマッ
チ し ま す 。 ソ ー ト に は現在のロケールの照合順序 (collating
sequance) と文字セットが用いられます。 [ の次の文字が ! また は
^ ならば、括られた文字に含まれない任意の文字がマッチします。範囲
表現における文字のソート順は、現在のロケール (およびシェル 変 数
LC_COLLATE が指定されていればその値) によって決定されます。 - は
、文字集合の最初または最後の文字として含めるとマッチングの対象に
で きます。 ] は、文字集合の最初の文字として含めるとマッチングの
対象にできます。
[ と ] の間では、文字クラス (character classes) を指定できます。
指定には [:class:] という記法を使います。ここで class は POSIX.2
標準で定義されている以下のクラスのいずれかです:
alnum alpha ascii blank cntrl digit graph lower print punct
space upper xdigit
文字クラスは、そのクラスの属する任意の文字にマッチします。
[ と ] の間では、同値クラス (equivalence class) を指定できます。
指定には [=c=] という記法を使います。これは現在のロケールにお け
る 定義において c と同じ照合重さ (collation weight) を持つ全ての
文字にマッチします。
[ と ] の間では、[.symbol.] という記述は照合シンボル symbol にマ
ッチします。
組 み込みコマンドの shopt を使ってシェルのオプション extglob が有効にさ
れていると、拡張パターンマッチング演算子がいくつか認識されるようにな り
ます。以下の説明では、pattern-list は | で区切られた 1 つ以上のパターン
のリストであるものとします。以下のサブパターンを 1 つあるいは複数使うこ
とにより、複合パターンを作れます。
?(pattern-list)
与 えられたパターンが 0 回または 1 回現われるとマッチしま
す。
*(pattern-list)
与えられたパターンが 0 回以上現われるとマッチします。
+(pattern-list)
与えられたパターンが 1 回以上現われるとマッチします。
@(pattern-list)
与えられたパターンのうち 1 つだけにマッチします。
!(pattern-list)
与えられたパターンいずれにも含まれないもの全てにマッチ し
ます。
クォートの削除
先に処理される展開の後、クォートされていない \, ’, " のうち、先の展開の
結果でないものは全て削除されます。
リダイレクト
シェルが解釈する特別な記法を用いると、コマンドの実行前に入出力を リダイ
レ クトできます。またリダイレクトを使うと、現在のシェル実行環境に対して
ファイルをオープンしたりクローズしたりできます。以下に示すリダイレク ト
演 算子は、 単純なコマンドの前や途中に置くことができ、また コマンドの後
に置けます。リダイレクトは左から右へと、現われた順に処理されます。
以下の説明においては、ファイル・ディスクリプター番号が省略され、かつ リ
ダイレクト演算子の最初の文字が < ならば、リダイレクトは標準入力 (ファイ
ル・ディスクリプター 0) を参照します。リダイレクト演算子の最初の文字 が
> ならば、リダイレクトは標準出力 (ファイル・ディスクリプター 1) を参照
します。
以下の説明では、リダイレクト演算子の次の単語に対しては、特に説明しな い
限 り、ブレース展開・チルダ展開・パラメータ展開・コマンド置換・算術式展
開・クォート削除・パス名展開・単語分割が行われます。ある単語が複数の 単
語に展開された場合はエラーになります。
リ ダイレクトの順番には意味がある点に注意してください。例えば、次のコマ
ンド
ls > dirlist 2>&1
は標準出力と標準エラー出力を両方ともファイル dirlist に書き込みますが、
次のコマンド
ls 2>&1 > dirlist
では標準出力だけがファイル dirlist に書き込まれます。なぜなら後者の場合
には、標準エラー出力は dirlist にリダイレクトされる前の標準出力の複製と
なるからです。
bash は、以下の表にあるようなファイル名がリダイレクトに使用されると、そ
れらを特別に扱います。
/dev/fd/fd
fd が有効な整数ならばファイル・ディスクリプター fd が複製
されます。
/dev/stdin
ファイル・ディスクリプター 0 が複製されます。
/dev/stdout
ファイル・ディスクリプター 1 が複製されます。
/dev/stderr
ファイル・ディスクリプター 2 が複製されます。
/dev/tcp/host/port
host が有効なホスト名またはインターネットアドレスで port
が整数のポート番号ならば、 bash は対応するソケットに対 し
て TCP 接続のオープンを試みます。
/dev/udp/host/port
host が有効なホスト名またはインターネットアドレスで port
が整数のポート番号ならば、 bash は対応するソケットに対 し
て UDP 接続のオープンを試みます。
ファイルのオープンや作成に失敗すると、リダイレクトも失敗します。
入力のリダイレクト
入 力をリダイレクトすると、 word を展開した結果の名前を持つファイルがオ
ープンされ、ファイル・ディスクリプター n で読み込めるようになります。 n
が 指定されていなければ、読み込みは標準入力 (ファイル・ディスクリプター
0) で行われます。
入力のリダイレクトは、一般的には以下の形式です:
[n]word
リダイレクト演算子が > であり、かつ noclobber オプションが組み込みコ マ
ン ド set に対して設定されている場合、word の展開で得たファイルが存在し
、かつそれが通常ファイルならば、リダイレクトは失敗します。リダイレク ト
演 算子が >| の場合や、リダイレクト演算子が > で組み込みコマンド set に
対する noclobber オプションが設定されていない場合、 word という名前のフ
ァイルが存在していてもリダイレクトが試みられます。
リダイレクトによる追加出力
こ の形式を使って出力のリダイレクトを行うと、 word を展開した結果の名前
を持つファイルがオープンされ、ファイル・ディスクリプター n に対する出力
がこのファイルに追加されるようになります。 n を指定しなければ、標準出力
(ファイル・ディスクリプター 1) で追加されます。ファイルが存在しなければ
、新しく作られます。
追加出力は一般的には以下の形式です:
[n]>>word
標準出力と標準エラー出力のリダイレクト
こ の構造を使うと、標準出力 (ファイル・ディスクリプター 1) と標準エラー
出力 (ファイル・ディスクリプター 2) の両方を、 word を展開した結果の 名
前を持つファイルにリダイレクトできます。
標準出力と標準エラー出力に対する形式は 2 つあります:
&>word
および
>&word
両者のうち望ましいのは前者の方です。これは次のものと同じ意味です:
>word 2>&1
ヒアドキュメント(Here Documents)
こ の形式のリダイレクトを用いると、シェルは現在のソースから入力を読み込
みます。この読み込みは word を単独で含む行 (末尾にブランク文字があっ て
は いけません) が現われるまで続きます。その行までに読み込んだ行は、コマ
ンドの標準入力として扱われます。
ヒアドキュメントの形式を以下に示します:
<<[-]word
here-document
delimiter
word に対するパラメータ展開・コマンド置換・算術式展開・パス名展開は全く
行 わ れません。 word が一部でもクォートされている場合は、 delimiter は
word のクォートをほどいた結果 (クォート文字を削除した結果) となり、ヒア
ド キュメントに含まれる行では展開が行われなくなります。 word がクォート
されていなければ、ヒアドキュメント中の全ての行に対してパラメータ展開 ・
コ マンド置換・算術式展開が行われます。後者の場合には \ という
文字列は無視されます (出力から取り除かれます)。また \, $, ‘ といった 文
字は \ を用いてクォートしなければなりません。
リ ダ イレクト演算子が <<- ならば、行頭にあるタブ文字は全て入力行および
delimiter を含む行から取り除かれます。これにより、シェルスクリプト中 の
ヒアドキュメントを自然な形でインデントさせることができます。
ファイル・ディスクリプターの複製
リダイレクト演算子
[n]<&word
を使うと入力ファイル・ディスクリプターを複製できます。 word が 1 桁以上
の数値に展開された場合、 n で示されるファイル・ディスクリプターが生成さ
れ 、そのファイル・ディスクリプターのコピーとなります。 word に含まれる
数値が入力のためにオープンされたファイル・ディスクリプターを指してい な
い場合、リダイレクト・エラーが起きます。 word を評価した結果が - となっ
た場合、ファイル・ディスクリプター n はクローズされます。 n が指定さ れ
ていない場合、標準入力 (ファイル・ディスクリプター 0) が使われます。
同様に、演算子
[n]>&word
を使って出力ファイル・ディスクリプターを複製できます。 n が指定されてい
ない場合は、標準出力 (ファイル・ディスクリプター 1) が使われます。 word
に 含まれる数値が、出力のためにオープンされたファイル・ディスクリプター
を指していない場合、リダイレクト・エラーが起きます。特別な場合ですが 、
n が省略され、かつ word が 1 桁以上の数字には展開されなかった場合、前に
説明したように標準出力と標準エラー出力がリダイレクトされます。
読み書きのためのファイル・ディスクリプターのオープン
リダイレクト演算子が
[n]<>word
ならば、 word を展開した結果の名前を持つファイルがファイル・ディスク リ
プ ター n での読み書きのためにオープンされます。 n が指定されていなけれ
ば、ファイル・ディスクリプター 0 で読み書きが行われます。ファイルが存在
しなければ、新しく生成されます。
エイリアス
エ イリアス(alias) を使うと、ある単語が単純なコマンドの先頭の単語として
使われた場合に、この文字列を別の単語に置換できます。シェルはエイリア ス
の リストを管理しています。このリストは組み込みコマンドの alias と una-
lias を使って設定および設定の取り消しできます (後述の シェルの組み込 み
コマンドを参照)。各コマンドの最初の単語がクォートされていない場合、エイ
リアスかどうかが確認され、エイリアスならばその単語はそのエイリアスの テ
キ ストと置換されます。エイリアス名と置換されるテキストには、シェルの入
力として有効なものは何でも含めることができます。これには先に挙げた メタ
文字も含まれますが、例外としてエイリアス名に = を含めることはできません
。置換されるテキストの最初の単語に対してもエイリアスかどうかの評価が さ
れ ますが、最初の単語が展開されるエイリアスと同じ場合には展開は 1度しか
行われません。つまり ls が ls -F のエイリアスとなっているような場合には
、 bash は置換される文字列を再帰的に展開することはありません。エイリア
スの値の最後の文字が ブランク文字の場合、エイリアスに続く次のコマンドの
単語に対してもエイリアス展開が試みられます。
エ イリアスは alias コマンドで作成とリスト表示を行い、 unalias コマンド
で削除します。
置換されるテキストに引き数を入れる仕組みはありません。引き数が必要な ら
ば、シェル関数を使わなければなりません (後述の 関数を参照)
シェルが対話的でない時には、 shopt コマンドによって expand_aliases オプ
ションが設定されていない場合に限り、エイリアスの展開は行われません ( 後
述のシェルの組み込みコマンドにおける shopt の説明を参照)。
エイリアスの定義や利用に関係する規則には、紛らわしい点があります。 bash
は、ある行に書かれているコマンドを実行する前に必ず、少なくとも 1 回は行
全 体を読み込みます。エイリアスが展開されるのはコマンドを読み込んだ時で
あり、実行する時ではありません。したがって、別のコマンドと同じ行でエ イ
リ アス定義を行った場合には、次の入力行が読み込まれるまではエイリアスの
効果は現われません。同じ行にあるエイリアス定義の後のコマンドは、新し い
エ イリアスの影響を受けません。この動作は関数を実行する場合にも問題にな
ります。エイリアスが展開されるのは関数定義が読み込まれる時であり、関 数
が 実行される時ではありません。なぜなら、関数定義自身も複合コマンドだか
らです。その結果として、関数内で定義されたエイリアスは、その関数が実 行
さ れるまでは利用できません。安全のため、エイリアス定義は独立した行で行
うべきです。複合コマンド内で alias を使ってはいけません。
ほとんど全ての用途において、シェル関数でエイリアスを代用できます。
関数
シェル関数は、後で使うために一連のコマンドを保存するものです。シェル 関
数の定義は既に シェルの文法で説明しています。シェル関数名が単純なコマン
ド名として使われた場合、関数名に対応するコマンド群が実行されます。関 数
は 現在のシェルのコンテキスト内で実行されます。つまり、新しいプロセスを
生成して関数を処理することはありません (これはシェルスクリプトと対照 的
な点です)。関数の実行中には、関数に与えた引き数が位置パラメータとなりま
す。特殊パラメータ # は更新され、この変更が反映されます。位置パラメータ
0 は変わりません。関数の実行中は FUNCNAME 変数に関数の名前が設定されま
す。シェル実行環境の状態は全て、関数とその呼び出し側で同じになります が
、 例外として DEBUG トラップ (後述の シェルの組み込みコマンドの項で、組
み込みコマンド trap の説明を参照) は継承されません。
関数ローカルの変数は、組み込みコマンド local で宣言できます。普通は、変
数とその値は関数とその呼び出し側で共有されます。
組 み込みコマンド return が関数中で実行された場合、関数は終了し、関数呼
び出しの次のコマンドから実行が再開されます。関数の終了時には、位置パ ラ
メータの値と特殊パラメータ # の値は、関数の実行前の値に戻ります。
関 数 の 名 前と定義をリスト表示するには、組み込みコマンドの declare や
typeset を、オプション -f を付けて実行します。 declare や typeset を オ
プ ション -F で実行すると、関数名だけがリスト表示されます。関数をエクス
ポートして、サブシェルでその関数が自動的に定義されている状態にできま す
。 これを行うには、組み込みコマンドの export に -f オプションを付けて実
行します。
関数は再帰させることができます。再帰呼び出しの回数には制限はありませ ん
。
算術式評価
シ ェルにおいては、特定の状況下で算術式を評価させることができます (組み
込みコマンドの let と 算術式展開 を参照)。評価は long 型の整数として 行
わ れ、オーバーフローのチェックは行われません。ただし、0 での除算はトラ
ップされ、エラーとしてのフラグが立てられます。演算子とその優先度、結 合
規則は C 言語と同じです。以下のリストは、同じ優先度を持つ演算子をグルー
プとしてまとめて列挙したものです。優先度の高いものから順に列挙してい ま
す。
id++ id--
変数を評価し、その後 increment (加算)/ decrement (減算) する。
++id --id
変数を increment (加算) / decrement (減算) してから評価する。
- + 単項式の負と正
! ~ 論理的否定とビット単位の否定
** 指数 (累乗)
* / % 乗算、除算、剰余
+ - 加算と減算
<< >> 左ビットシフトと右ビットシフト
<= >= < >
比較
== != 等値と非等値
& ビット単位の AND
^ ビット単位の排他的 OR
| ビット単位の OR
&& 論理的 AND
|| 論理的 OR
expr?expr:expr
条件付き実行
= *= /= %= += -= <<= >>= &= ^= |=
代入
expr1 , expr2
コンマ
シ ェル変数をオペランドにすることもできます。パラメータ展開は式の評価よ
り前に行われます。式の中では、パラメータの値は long 型の整数に強制的 に
変 換 されます。式の中では、シェル変数を (パラメータ展開規則を用いずに)
変数名で参照できます。変数の値は変数が参照された際に算術式として評価 さ
れ ます。式で用いるためにシェル変数の整数属性を有効にする必要はありませ
ん。
先頭が 0 である定数は 8 進数として解釈されます。先頭が 0x または 0X な
ら ば 16 進数として解釈されます。それ以外の場合には、数値は [base#]n の
形式で表します。ここで base は 2 から 64 の間の 10 進数であり、算術的な
意味での基数を表します。 n はその基数における数を表します。ある桁におい
て 9 より大きい数字を表すには文字を使います。文字を使う場合には、アルフ
ァベット小文字、大文字、_, @ をこの順番で使います。 base が 36 以下の場
合には、大文字と小文字は区別されず、大文字と小文字のどちらを使っても 10
から 35 までの数字を表現できます。
演 算子は優先度の順に評価されます。括弧内にある部分式は最初に評価され、
前述の優先規則よりも優先させることができます。
条件式
条件式は複合コマンド [[ と組み込みコマンドの test および [ によって使用
で き、ファイルの属性を調べたり、文字列比較や算術式比較を行ったりできま
す。式は以下に示す単項のプライマリや二値のプライマリから構成されます 。
プライマリのいずれかに対する file 引き数が /dev/fd/n という形式ならば、
ファイル・ディスクリプター n が調べられます。プライマリのいずれかに対す
る file 引き数が /dev/stdin、/dev/stdout、/dev/stderr のいずれかであれ
ば、 対応するファイル・ディスクリプターが調べられます 。 ( /dev/stdin
、/dev/stdout、/dev/stderr に対応するファイル・ディスクリプターはそれぞ
れ 0、1、2 です。)
-a file
file が存在すれば真となります。
-b file
file が存在し、かつブロック特殊ファイルならば真となります。
-c file
file が存在し、かつキャラクタ特殊ファイルならば真となります。
-d file
file が存在し、かつディレクトリならば真となります。
-e file
file が存在すれば真となります。
-f file
file が存在し、かつ通常ファイルならば真となります。
-g file
file が存在し、かつ set-group-id されていれば真となります。
-h file
file が存在し、かつシンボリックリンクならば真となります。
-k file
file が存在し、かつ ‘‘sticky’’ ビットが設定されていれば真とな り
ます。
-p file
file が存在し、かつ名前付きパイプ (FIFO) ならば真となります。
-r file
file が存在し、かつ読み込み可能ならば真となります。
-s file
file が存在し、かつそのサイズが 0 より大きければ真となります。
-t fd ファイル・ディスクリプター fd がオープンされており、かつ端末を参
照していれば真となります。
-u file
file が存在し、かつ set-user-id ビットが設定されていれば真となり
ます。
-w file
file が存在し、かつ書き込み可能ならば真となります。
-x file
file が存在し、かつ実行可能ならば真となります。
-O file
file が存在し、かつ (実行中のシェルの) 実効ユーザ ID に所有され
ていれば真となります。
-G file
file が存在し、かつ (実行中のシェルの) 実効グループ ID に所有 さ
れていれば真となります。
-L file
file が存在し、かつシンボリックリンクならば真となります。
-S file
file が存在し、かつソケットならば真となります。
-N file
file が存在し、かつ前回読み込まれた後に修正されていれば真となり
ます。
file1 -nt file2
file1 が (変更日時に関して) file2 より新しければ真となります。
file1 -ot file2
file1 が file2 より古ければ真となります。
file1 -ef file2
file1 と file2 とでデバイス番号と i-ノード番号が同じならば真とな
ります。
-o optname
シ ェルオプション optname が有効ならば真となります。後述する組み
込みコマンド set に対するオプションの説明中にあるオプション一 覧
を参照してください。
-z string
string の長さが 0 ならば真となります。
-n string
string string の長さが 0 でなければ真となります。
string1 == string2
文字列が同じならば真となります。== の代わりに = も使えます。
string1 != string2
2 つの文字列が異なれば真となります。
string1 < string2
現 在のロケールにおいて、string1 が string2 よりも辞書順で前にあ
る場合に真となります。
string1 > string2
現在のロケールにおいて、string1 が string2 よりも辞書順で後に あ
る場合に真となります。
arg1 OP arg2
OP は -eq, -ne, -lt, -le, -gt, -ge のいずれかです。これらの二値
演算子が真を返すのはそれぞれ、 arg1 が arg2 に対して等しい場合、
等しくない場合、小さい場合、小さいか等しい場合、大きい場合、大き
いか等しい場合です。 arg1 や arg2 には、正または負の整数を使用で
きます。
単純なコマンドの展開
単 純なコマンドを実行すると、シェルは以下に示す展開、代入、リダイレクシ
ョンを左から右の順で実行します。
1. パーザが変数代入 (コマンド名の前にあるもの) またはリダイレクショ
ンと判断した単語は、保存されて後で処理されます。
2. 変数代入でもリダイレクションでもない単語が展開されます。もし展開
の後に残っている単語があれば、その最初の単語がコマンド名となり、
残りが引き数となります。
3. リダイレクションが前述の リダイレクションで説明したように実行さ
れます。
4. 変数代入の = の後にあるテキストに対して、チルダ展開、パラメー タ
展開、コマンド置換、算術式展開、クォート削除が行われます。この処
理は変数を代入する前に行われます。
コマンド名が残らなかった場合には、変数を代入した結果が現在のシェル環 境
に 効果を及ぼします。そうでない場合、変数は実行されるコマンドの環境に追
加されるだけで、現在のシェル環境には影響を与えません。読み込み専用の 変
数に対して代入をしようとするとエラーが発生し、そのコマンドは 0 でないス
テータスで終了します。
コマンド名が残らなかった場合、リダイレクションは行われますが、現在の シ
ェ ル環境は影響を受けません。リダイレクションのエラーが起きると、コマン
ドは 0 でないステータスで終了します。
展開の後にコマンド名が残っている場合、後述するように実行が進行します 。
そ うでない場合はコマンドは終了します。展開のいずれかがコマンド置換であ
る場合には、コマンドの終了ステータスは最後に実行されたコマンド置換の 終
了 ステータスになります。コマンド置換が行われなかった場合には、コマンド
はステータス 0 で終了します。
コマンドの実行
コマンドが単語に分割された後に、単純なコマンドとそれに対する引き数リ ス
ト (引き数リストは省略可能) となった場合、以下の動作が行われます。
コ マンド名にスラッシュが含まれない場合、シェルはコマンドの位置を特定し
ようとします。その名前のシェル関数が存在すれば、前に 関数で説明したよう
に その関数が呼び出されます。名前が関数にマッチしない場合には、シェルは
シェルの組み込みコマンドのリストを探します。マッチするものがあった場 合
、その組み込みコマンドが呼び出されます。
名 前がシェル関数も組み込みコマンドでなく、かつスラッシュを含まない場合
には、 bash は PATH の各要素を検索し、その名前の実行ファイルを含むデ ィ
レ クトリを探します。 bash はハッシュ表を使って実行ファイルの完全なパス
名を記憶します (後述の シェルの組み込みコマンドの hash の項を 参 照) 。
PATH に含まれるディレクトリの完全な探索は、そのコマンドがハッシュ表の中
に無い場合にのみ行われます。検索にも失敗すると、シェルはエラーメッセ ー
ジを出力し、終了ステータス 127 を返します。
検索に成功したか、コマンド名に 1 つ以上のスラッシュが含まれる場合には、
シェルは指定されたプログラムを独立した実行環境で実行します。引き数 0 に
は 指定された名前が設定され、コマンドに対する残りの引き数には (もしあれ
ば) 指定された引き数が設定されます。
このファイルが実行可能フォーマットでないために実行が失敗し、かつディ レ
クトリでもない場合には、このファイルは シェルスクリプト(shell script)で
あると見なされます。シェルスクリプトとは、シェルのコマンドが書かれて い
る ファイルのことです。シェルスクリプトを実行するためにサブシェルが呼び
出されます。このサブシェルは自分自身を再初期化し、シェルスクリプトを 処
理 するために新しいシェルが起動されたかのような結果になります。ただし、
親が記憶しているコマンドの位置 (後述のシェルの組み込みコマンドにおけ る
hash の項を参照) は子にも引き継がれます。
プログラムが #! で始まるファイルである場合、最初の行の残りの部分はこの
プログラムのインタプリタを指定します。シェルは指定されたインタプリタ を
オ ペレーティングシステム上で実行します。オペレーティングシステムは、こ
の実行可能フォーマットを直接処理しません。インタプリタに対する引き数 は
、プログラムの先頭の行のインタプリタ名の後の省略可能な引き数 1 つと、そ
の後のプログラム名、さらに (もしあれば) その後のコマンドへの引き数か ら
構成されます。
コマンド実行環境
シェルは以下の要素からなる実行環境(execution environment)を持ちます:
· 起動時にそのシェルが継承したオープンされているファイル。これは組
み込みコマンド exec に与えられているリダイレクション機能で変更さ
れます。
· 現 在の作業ディレクトリ (current working directory)。これは cd,
pushd, popd で設定するか、あるいは起動時にそのシェルが継承します
。
· ファイル作成モードのマスク。これは umask で設定するか、あるいは
そのシェルの親から継承します。
· trap で設定された現在のトラップ。
· シェルのパラメータ。これは変数の代入か set で設定されるか、あ る
いはその環境内にある親シェルから継承します。
· 実行中に定義されるか、その環境内にある親シェルから継承したシェル
関数。
· 起動時に有効にしたか (デフォルト値あるいはコマンドライン引き数で
設定した値)、 set で有効にしたオプション。
· shopt で有効にしたオプション。
· alias で定義したシェルエイリアス。
· 各種プロセスID。これにはバックグラウンドジョブや $$ の値、 $PPID
の値が含まれます。
組み込みコマンドやシェル関数を除く単純なコマンドを実行するとき、この コ
マ ンドは独立した実行環境内で呼び出されます。この環境は以下の要素から成
り立っています。特に断らない限り、この値はシェルから引き継がれます。
· シェルのオープンしているファイルと、コマンドに対するリダイレクシ
ョンで指定した変更・追加をこれに加えたもの。
· 現在の作業ディレクトリ
· ファイル作成モードのマスク
· エクスポートするシェル変数と、そのコマンドに対してエクスポートさ
れた変数。これらは環境で渡されます。
· シェルが捕捉したトラップは、そのシェルの親から継承された値に再設
定されます。そのシェルが無視したトラップは無視されます。
こ の独立の環境内で呼び出されたコマンドが、 (親である) シェルの実行環境
に影響を及ぼすことはできません。
コマンド置換と非同期コマンドは、サブシェル環境内で呼び出されます。こ の
サ ブシェル環境はシェル環境を複製したものです。ただし、シェルが捕捉した
トラップは、そのシェルの起動時に親から継承した値に再設定されます。パ イ
プ ラインの一部として起動された組み込みコマンドは、サブシェル環境で実行
されます。サブシェル環境に対して行われた変更は、元のシェル実行環境に 影
響を及ぼすことはできません。
環境
プ ログラムの起動時には、 環境 (environment) と呼ばれる文字列の配列が渡
されます。これは 変数名-値 のペアからなるリストで、 変数名=値という形に
なります。
シ ェルは、環境を操作する様々な方法を提供しています。起動時には、シェル
は自分自身の環境を調べ、見つかった名前それぞれに対してパラメータを生 成
し、それに自動的に印を付けて子プロセスに エクスポート (export) します。
実行されたコマンドは環境を継承します。 export コマンドまたは declare -x
コ マンドを用いると、パラメータや関数の追加と削除を環境に対して行えます
。環境内のパラメータの値が変更されると、新しい値は環境の一部となり、 古
い 値と置き換わります。実行されたコマンドが継承する環境は、シェルの最初
の環境から、変数の値がシェル中で変更されたり、一部のペアが unset コマン
ド で削除されたり、 export コマンドや declare -x コマンドで追加されたり
したものになります。
単純なコマンドや関数に対する環境は、一時的に修正できます。これは、既に
パ ラメータの項で説明したように、パラメータ代入を前に置くことで行います
。このような代入が影響を与えるのは、そのコマンドが参照する環境だけで す
。
-k オプションを設定 (後述の組み込みコマンド set を参照) すると、コマン
ド名の前に置いたものだけではなく、 全てのパラメータ代入がそのコマンドの
環境に影響を与えます。
bash が外部コマンドを起動したときには、変数 _ にはコマンドの完全なファ
イル名が設定され、環境変数としてそのコマンドに渡されます。
終了ステータス
シェルは、終了コード 0 で終了したコマンドは正常終了したとみなします。終
了 コード 0 は成功を示します。 0 以外の終了コードは失敗を示します。ある
コマンドが致命的なシグナル N で終了したときには、 bash は「128+N」の 値
を終了ステータスに使います。
コ マンドが見つからなかった場合には、そのコマンドを実行するために生成さ
れた子プロセスがステータス 127 を返します。コマンドが見つかったけれど実
行できなかった場合には、返却ステータスは 126 です。
展 開やリダイレクションの際のエラーのためにコマンドが失敗した場合には、
0 より大きい終了ステータスが返されます。
シェルの組み込みコマンドは、成功した場合にはステータス 0 (真) を返し 、
実行中にエラーが起こった場合には 0 でない値 (偽) を返します。
bash 自身が返す終了ステータスは、文法エラーが起きなければ、実行した最後
のコマンドの終了ステータスです。文法エラーの場合には 0 でない値が終了ス
テータスとなります。後述の組み込みコマンド exit も参照してください。
シグナル
bash が対話的であり、トラップが全く無いとき、bash は SIGTERM を無視し (
したがって kill 0 では対話シェルは kill されません)、 SIGINT を捕捉、処
理します (したがって組み込みコマンド wait は割り込み可能です)。どんな場
合でも、bash は SIGQUIT を無視します。ジョブ制御が有効な状態な ら ば 、
bash は SIGTTIN, SIGTTOU, SIGTSTP を無視します。
bash が起動した同期ジョブは、シェルが自分の親から継承した値をシグナルハ
ンドラに設定します。ジョブ制御が有効でないときには、非同期コマ ン ド は
SIGINT と SIGQUIT も無視します。コマンド置換の結果として実行されたコマ
ンドは、キーボードで生成されたジョブ制御シグナルを無視します。無視さ れ
るシグナルは SIGTTIN, SIGTTOU, SIGTSTP です。
デ フォルトでは、シェルは SIGHUP を受け取ると終了します。終了する前には
、シェルは実行中・停止中の全てのジョブに対して SIGHUP を再送信します 。
停止しているジョブには SIGCONT が送られ、このジョブが SIGHUP を受け取る
ようにします。特定のジョブに対してシェルからシグナルが送られないよう に
す るためには、組み込みコマンド disown (後述の シェルの組み込みコマンド
を参照) を使って、そのジョブをジョブテーブルから削除するか、あ る い は
disown -h を使って、 SIGHUP を受け取らないようにマークを付けます。
シ ェルオプションの huponexit が shopt を使って設定された場合、対話的な
ログインシェルが終了するときに、 bash は SIGHUP を全てのジョブに送り ま
す。
コ マンドの完了を待っている間に、トラップが設定されたシグナルを bash が
受け取ったとき、そのトラップはコマンドが完了するまで実行されま せ ん 。
bash が組み込みコマンドの wait を使って非同期コマンドを待っている時に、
トラップが設定されているシグナルを受け取ると、組み込みコマンド wait は
即座に復帰させられます。この際の終了ステータスは 128 より大きい値になり
ます。また復帰するのはトラップが実行された直後です。
ジョブ制御
ジョブ制御(job control) とは、プロセスの実行を選択的に停止 (サ ス ペ ン
ド/suspend) させ、後に再び実行を続けさせる (リジューム/resume) 機能のこ
とです。ユーザは通常、システムの端末ドライバと bash を組み合わせて使 い
、対話的インタフェースを通してこの機能を利用します。
シェルはパイプラインごとに ジョブ(job) を構成します。シェルは現在実行中
のジョブのテーブルを保存しています。このテーブルは jobs コマンドを使 っ
て リ スト表示できます。 bash がジョブを非同期的に (バックグラウンドで)
起動したときには、 bash は以下のような行を出力します:
[1] 25647
これは、このジョブのジョブ番号は 1 であり、このジョブを構成するパイプラ
イ ン中の最後のプロセスの ID が 25647 であることを示しています。 1 つの
パイプラインに含まれる全てのプロセスは同じジョブのメンバです。 bash は
、ジョブ制御の基礎として ジョブという抽象化機構を使います。
ジ ョブ制御のためのユーザインタフェースの実装を容易にするためにオペレー
ティングシステムは現在の端末プロセスのグルー プ ID (current terminal
process group ID) という情報を管理しています。このプロセスグループのメ
ンバ (プロセスグループ ID が現在の端末プロセスのグループ ID と等しい プ
ロ セス) は、 SIGINT のような、キーボードで生成されたシグナルを受け取り
ます。このようなプロセスは フォアグラウンド (foreground) にあると言われ
ま す。 バックグラウンド (background) プロセスは、プロセスのグループ ID
が端末のグループ ID と異なるプロセスです。このようなプロセスは、キー ボ
ー ドで生成したシグナルの影響を受けません。端末への読み書きが許されるの
はフォアグラウンドプロセスだけです。バックグラウンドプロセスが端末か ら
の 読み込み (端末への書き込み) を行おうとすると、このプロセスには端末ド
ライバから SIGTTIN (SIGTTOU) シグナルが送られます。このシグナルを捕捉し
なければ、プロセスは停止します。
bash を動かしているオペレーティングシステムがジョブ制御をサポートしてい
るならば、ユーザは bash を使ってジョブ制御を行えます。プロセスの動作 中
に サスペンド文字(通常は ^Z, Control-Z) を打ち込むと、そのプロセスは停
止させられ、 bash に制御が戻ります。 遅延サスペンド (delayed suspend)
文 字 (通常は ^Y, Control-Y) を打ち込むと、そのプロセスは端末から入力を
読み込もうとしたときに停止させられ、制御が bash に戻ります。このとき ユ
ー ザはこのジョブの状態を操作できます。利用できるのは、バックグラウンド
で実行を継続するならば bg コマンド、フォアグラウンドで実行を継続する な
らば fg コマンド、プロセスを kill するなら kill コマンドです。^Z の効果
は即座に現われるので、未出力の出力や先行入力した文字が破棄されるとい う
副作用があります。
シェル上でジョブを参照する方法は色々あります。文字 % はジョブ名の始まり
を示します。ジョブ番号 n は %n として参照できます。ジョブの参照には、ジ
ョ ブを起動する時に使った名前の先頭部分やコマンドライン中に現われる部分
文字列を使うこともできます。例えば、 %ce は停止しているジョブ ce を指し
ま す。先頭の部分がマッチするジョブが複数個ある場合には、 bash はエラー
を報告します。一方、 %?ce を用いると、文字列 ce をコマンドライン中に 含
む 任意のジョブを参照できます。部分文字列がマッチするジョブが複数個ある
場合には、 bash はエラーを報告します。シンボル %% および %+ は、シェ ル
が 覚えている カレントジョブ (current job) を指します。これは、フォアグ
ラウンドで起動されている時に停止されたか、バックグラウンドで起動され た
最後のジョブです。 前のジョブ (previous job) は %- を使って参照できます
。jobs コマンドの出力においては、カレントジョブには必ず + というフラ グ
が付き、前のジョブには - というフラグが付きます。
単 にジョブを呼べば、そのジョブをフォアグラウンドに持ってきます。つまり
、 %1 は ‘‘fg %1’’ と同義であり、ジョブ 1 をバックグラウンドからフォ ア
ウグラウンドに持ってきます。同様に ‘‘%1 &’’ はジョブ 1 をバックグラウン
ドで実行再開させます。これは ‘‘bg %1’’ と同じ意味です。
ジョブの状態が変わると、シェルはそれを即座に知ります。 bash がジョブ の
状 態変化を報告するのは通常、プロンプトを出力する直前です。これは他の出
力を妨害しないためです。組み込みコマンド set で -b オプションが指定され
ていると、 bash はこのような変化を即座に報告します。
ジ ョブを停止させたままで bash を終了 (exit) させようとすると、シェルは
警告メッセージを出力します。このような時には、 jobs コマンドを使って ジ
ョ ブの状態を調べられます。間にコマンドを挟まずに bash を再び終了させよ
うとすると、シェルは警告を繰り返さないで、停止されているジョブを終了 さ
せます。
プロンプト
対 話的に動作している場合、 bash はコマンドを読む込み準備ができた時にプ
ライマリプロンプト PS1 を表示し、コマンドを完成させるためにまだ入力が必
要な時にセカンダリプロンプト PS2 を表示します。 bash ではこれらのプロン
プト文字列をカスタマイズできます。この際にはバックスラッシュでエスケ ー
プされた各種特殊文字を挿入でき、これは以下のようにデコードされます:
\a ASCII のベル文字 (07)
\d "曜日 月 日" という形式の日付 (例: "Tue May 26")
\e ASCII のエスケープ文字 (033)
\h ホスト名のうち最初の ‘.’ までの部分
\H ホスト名
\j シェルによって現在管理されているジョブの数
\l シェルの端末デバイスのベース名 (basename)
\n 改行
\r 復帰
\s シェルの名前。つまり $0 のベース名 (最後のスラッシュ以降
の部分)
\t 24 時間の HH:MM:SS 形式の現在の時刻
\T 12 時間の HH:MM:SS 形式の現在の時刻
\@ 12 時間の HH:MM am/pm 形式の現在の時刻
\u 現在のユーザのユーザ名
\v bash のバージョン (例: 2.00)
\V bash のリリース。バージョンにパッチレベルを加えたもの (例
: 2.00.0)
\w 現在の作業ディレクトリ
\W 現在の作業ディレクトリのベース名
\! このコマンドの履歴番号
\# このコマンドのコマンド番号
\$ 実効 UID が 0 の場合に #、それ以外の場合は $
\nnn 8進数 nnn に対応する文字
\\ バックスラッシュ
\[ 非表示文字のシーケンスの開始。これを使うと、プロンプト中
に端末の制御シーケンスを埋め込むことができます。
\] 非表示文字のシーケンスを終了します。
コマンド番号と履歴番号は異なるのが普通です: コマンドの履歴番号とは履 歴
リ スト内での位置です。履歴リストは履歴ファイルから読み込めます。 (後述
の 履歴を参照) 一方コマンド番号は、現在のシェルのセッション中に実行され
た 一連のコマンドの列における位置です。この文字列がデコードされた後、さ
らにパラメータ展開、コマンド置換、算術式展開、クォート削除が適用され ま
す 。展開はシェルオプション promptvars (後述の シェルの組み込みコマンド
の項にある shopt コマンドの説明を参照) の値に基づいて行われます。
READLINE ライブラリ
readline は対話シェルを使うときに入力の読み込みを処理するライブラリです
。ただし、シェルの起動時に --noediting オプションが指定された場合には使
われません。デフォルトでは、行編集に使うコマンドは emacs のコマンドに似
て います。 vi 形式の行編集インタフェースも使えます。シェルを起動した後
に行編集機能を無効にするには、組み込みコマンド set (後述の シェルの組み
込みコマンドを参照) に対して +o emacs オプションまたは +o vi オプション
を設定してください。
Readline セクションにおける記法
このセクションでは、emacs 形式の記法を使ってキーストロークを表します 。
コントロールキーは C-key で表します (例: C-n は Control-N の意味です)。
同様に メタキーは M-key で表すので、M-x は Meta-X を表すことになりま す
。 (メタキーが無いキーボードでは、M-x は ESC x を表します。つまり、エス
ケープキーを押した後に x キーを押します。これは ESC をメタプレフィッ ク
ス (meta prefix) にする操作です。 M-C-x の組み合わせは、ESC-Control-x
あるいはエスケープキーを押した後に、コントロールキーを押したまま x を押
すことを示します。)
Readline のコマンドには数値の 引き数を指定できます。通常これは繰り返し
の回数として作用します。ただし場合によっては、引き数の符号が意味を持 つ
こともあります。前方に作用するコマンド (例: kill-line) に負の引き数を渡
すと、コマンドは後方に作用します。引き数に対する動作がこの説明と異な る
コマンドについては後で説明します。
コ マンドがテキストをキル (kill) すると説明されている時は、削除されたテ
キストは、後で取り出せる (ヤンク (yank) できる) ように保存されます。 キ
ルされたテキストは、キルリング (kill ring) に保存されます。連続してキル
を行うと、テキストは 1 つのまとまりとして保存されるので、全部を一度にヤ
ン クできます。テキストをキルしないコマンドが挟まると、キルリング上のテ
キストが分離されます。
Readline の初期化
コマンドを初期化ファイル (inputrc ファイル) に追加すると、 readline を
カスタマイズできます。このファイルの名前は、変数 INPUTRC の値から決まり
ます。この変数が設定されていない場合のデフォルト値は ~/.inputrc です 。
readline ライブラリを使うプログラムが起動する際には、この初期化ファイル
が読み込まれ、キー割り当てと変数が設定されます。 readline の初期化フ ァ
イ ル中で使用できる基本的構文は、以下のように少ししかありません。空行は
無視されます。 # で始まる行はコメントです。 $ で始まる行は条件文です 。
それ以外の行はキー割り当てと変数の設定です。
デフォルトのキー割り当ては inputrc ファイルで変更できます。このライブラ
リを使う他のプログラムからも、独自のコマンドとキー割り当てを追加でき ま
す。
例えば、
M-Control-u: universal-argument
や
C-Meta-u: universal-argument
を inputrc ファイルに書くと、M-C-u で readline の universal-argument コ
マンドが実行されるようになります。
認識されるシンボリックな文字名を以下に示します: RUBOUT, DEL, ESC, LFD,
NEWLINE, RET, RETURN, SPC, SPACE, TAB。
readline では、コマンド名だけでなくキーにも文字列を割り当てできます。つ
まり、そのキーが押されると文字列が挿入されます (マクロ, macro)。
Readline のキー割り当て
inputrc ファイルにおける制御キーの割り当て方は単純です。必要なものは 、
コ マンドの名前あるいはマクロのテキストと、これらが割り当てられるキーシ
ーケンスだけです。名前は 2 通りの方法で指定できます。つまり、シンボリッ
クなキーの名前 (たぶん、これに Meta- や Control- プレフィックスが付いた
もの) による指定と、キーシーケンスによる指定です。
「keyname:function-name」あるいは「keyname:macro」の形式を使うときに は
、 keyname は英語で書き下したキーの名前となります。例を以下に示します:
Control-u: universal-argument
Meta-Rubout: backward-kill-word
Control-o: "> output"
この例では、 C-u が universal-argument に、 M-DEL が backward-kill-word
に割り当てられます。また、 C-o はマクロの実行に割り当てられ、右辺値に展
開されます (つまり、テキスト ‘‘> output’’ が編集行に挿入されます)。
後 者の形式である「"keyseq":function-name」または「"keyseq":macro」にお
いては、 keyseq は先程の keyname とは異なり、ダブルクォートで括ってキー
シ ー ケンス全体を示す文字列を表記しています。以下の例で示すように、GNU
Emacs 形式のキーエスケープの一部を使えます。ただしシンボリックな文字 名
は認識されません。
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file
"\e[11~": "Function Key 1"
この例でも、 C-u が universal-argument 機能に割り当てられています。 C-x
C-r は re-read-init-file 機能に割り当てられ、 ESC [ 1 1 ~ は Function
Key 1 ‘‘Function Key 1’’. という文字列の挿入に割り当てられています。
GNU Emacs 形式のエスケープシーケンスを以下に全て示します:
\C- コントロールプレフィックス
\M- メタプレフィックス
\e エスケープ文字
\\ バックスラッシュ
\" " という文字
\’ ´ という文字
GNU Emacs 形式のエスケープシーケンスに加えて、別形式のバックスラッシュ
エスケープも使えます:
\a 警告 (ベル)
\b バックスペース
\d 削除 (delete)
\f フォームフィード
\n 改行
\r 復帰
\t 水平タブ
\v 垂直タブ
\nnn ASCII コードの 8 進値が nnn である文字 (1 文字につき数字
3 桁)
\xnnn ASCII コードの 16 進値が nnn である文字 (1 文字につき数字
3 桁)
マクロのテキストを入力する際には、マクロ定義を示すためにシングルクォ ー
ト やダブルクォートを使わなければなりません。クォートされていないテキス
トは関数名と見なされます。マクロ本体では、前述のバックスラッシュによ る
エ スケープは展開されます。バックスラッシュはマクロのテキスト内の他の文
字を全てエスケープします。これには " や ’ も含まれます。
bash では、組み込みコマンドの bind を使って、readline の現在の キー割り
当ての表示と変更を行えます。また組み込みコマンド set に対して -o オプシ
ョンを使えば、編集モードを対話的利用の途中に切替え可能です (後述の シェ
ルの組み込みコマンドを参照)。
Readline の変数
Readline の動作をカスタマイズできる変数は他にもあります。変数は inputrc
ファイル中に
set variable-name value
という形式の文で設定できます。特に断らない限り、readline の変数は On ま
たは Off のいずれかです。変数とそのデフォルト値を以下に示します:
bell-style (audible)
readline が 端末のベルを鳴らそうとしたときの動作を制御します。
none が設定されている場合は、readline はベルを鳴らし ま せ ん 。
visible が設定されている場合には、可能であれば可視ベル (visible
bell) が用いられます。audible が設定されている場合には 、 read-
line は端末のベルを鳴らそうとします。
comment-begin (‘‘#’’)
readline の insert-comment コマンドが実行されたときに挿入される
文字列です。このコマンドは emacs モードでは M-# に割り当て ら れ
、vi コマンドモードでは # に割り当てられます。
completion-ignore-case (Off)
On が設定されていると、 readline がファイル名のマッチングと補完
を行う際に大文字と小文字が区別されません。
completion-query-items (100)
possible-completions コマンドが生成した補完候補の数が、いくつ を
越えると表示の可否をユーザに問い合わせるのかを決めます。この変数
には 0 以上の任意の整数を設定できます。補完の候補数がこの変数 の
値以上の場合には、ユーザに対して候補を表示するかどうかの問い合わ
せがなされます。そうでない場合には、単に端末に補完の候補がリスト
表示されます。
convert-meta (On)
On を設定すると、readline は 8 番目のビットがセットされている文
字を ASCII のキーシーケンスに変換します。変換は、8 番目のビッ ト
を落として、エスケープ文字を前に追加することによって行います (実
際にはエスケープ文字をメタプレフィックスとして用います)。
disable-completion (Off)
On を設定すると、readline は単語の補完を行わなくなります。補完さ
れ る文字の編集行への挿入は、その文字を self-insert に割り当てた
かのように行われます。
editing-mode (emacs)
readline の起動時に emacs と vi のどちらに似たキー割り当てを使う
の かを制御します。 editing-mode には emacs と vi のいずれかを指
定できます。
enable-keypad (Off)
On を設定すると、 readline は呼び出された時にアプリケーション キ
ーパッドを有効にしようとします。一部のシステムでは、矢印キーを使
うためにこれを有効にする必要があります。
expand-tilde (Off)
on を設定すると、 readline が単語の補完を試みるときにチルダ展 開
が行われます。
horizontal-scroll-mode (Off)
on が設定されている時、readline は表示の際に行を 1 つしか使わな
いようになります。つまり行がスクリーンの幅より長くなると、新しい
行に折り返すのではなく、1 つの入力行の中で横にスクロールします。
input-meta (Off)
On が設定されていると、readline は 8 ビットの入力が可能になり ま
す(つまり、読み込んだ文字の再上位ビットを落としません)。この動作
は、端末のサポートとは無関係に行われます。 meta-flag という名 前
は、この変数の別名です。
isearch-terminators (‘‘C-[C-J’’)
インクリメンタル検索を終了させる文字からなる文字列です (終了後に
その文字がコマンドとして実行されることもありません)。この変数 に
値が設定されていなければ、 ESC と C-J でインクリメンタル検索が終
わります。
keymap (emacs)
現在の readline のキーマップを設定します。正しいキーマップ名を全
て 挙げると、 emacs, emacs-standard, emacs-meta, emacs-ctlx, vi,
vi-command, vi-insert となります。vi は vi-command と 等 価 で
、emacs は emacs-standard と等価です。デフォルト値は emacs です
。 editing-mode の値もデフォルトキーマップに影響を与えます。
mark-directories (On)
On が設定されていると、補完されたディレクトリ名の末尾にスラッ シ
ュが追加されます。
mark-modified-lines (Off)
On が設定されていると、履歴行を表示する際に、以前に変更されたも
のの先頭にアスタリスク (*) を付けて表示します。
output-meta (Off)
On が設定されていると、 readline は 8 番目のビットが立っている文
字を直接表示します。メタ文字を前置したエスケープシーケンスでの表
示は行いません。
print-completions-horizontally (Off)
On が設定されていると、 readline は補完でマッチするものをアル フ
ァベット順にして、縦方向ではなく横方向に並べて表示します。
show-all-if-ambiguous (Off)
これは補完機能のデフォルトの挙動を変えます。 On が設定されている
場合、単語に対する補完候補が複数個あると、マッチするものが即座に
リスト表示されます。ベルは鳴らされません。
visible-stats (Off)
On が設定されていると、 stat(2) で得られるファイルの種類を表す文
字が、補完候補のリスト表示の際に追加されます。
Readline の条件構文
Readline には、 C 言語のプリプロセッサの条件付きコンパイル機能と似た コ
ン セプトに基づく機能が実装されています。これを使うとキー割り当てや変数
の設定を評価の結果として実行できます。パーザディレクティブは 4 つありま
す。
$if $if 構文を使うと、編集モードや使っている端末、 readline を使って
いるアプリケーションに基づいた割り当てを行えます。評価文のテキス
トは行の最後までです。これを分離するには文字は必要ありません。
mode $if ディレクティブの mode= 形式は、 readline が emacs モ
ードか vi モードのどちらになっているかを調べるために使 い
ま す 。 例 え ばこれを set keymap コマンドと一緒に使い、
readline が emacs モードで始まった時だけキーの割り当て を
emacs-standard や emacs-ctlx キーマップに設定できます。
term term= 形式を使うと、端末固有のキー割り当てを入れることが
できます。これは端末のファンクションキーが出力するキー シ
ーケンスを割り当てる場合などに使えます。 = の右辺の単語は
、端末の完全な名前および最初の - の前までの部分的な名前の
両 方 に対して評価されます。これにより例えば、 sun は sun
と sun-cmd の両方にマッチできます。
application
application はアプリケーション固有の設定を入れるために 使
い ます。 readline ライブラリを使っているプログラムはそれ
ぞれアプリケーション名 (application name) を設定するの で
、 初期化ファイルはそれが特定の値かどうかを調べられます。
これを使って、キーシーケンスを特定のプログラム用の便利 な
機 能に割り当てできます。例えば以下のコマンドは、 bash 内
で現在または 1 つ前の単語をクォートするキーシーケンスを追
加します:
$if Bash
# Quote the current or previous word
"\C-xq": "\eb\"\ef\""
$endif
$endif このコマンドは上の例で見たように、$if コマンドを終了させます。
$else $if ディレクティブのこの分岐内におけるコマンドは、評価が失敗した
時に実行されます。
$include
このディレクティブはファイル名 1 つを引き数に取り、そのファイ ル
からコマンドとキー割り当てを読み込みます。例えば以下のディレクテ
ィブを使うと /etc/inputrc が読み込まれます:
$include /etc/inputrc
検索
readline には、指定した文字列を含む行をコマンド履歴内から探すコマンドが
用意されています (後述の 履歴を参照)。検索のモードには、 インクリメンタ
ル (incremental) モードと 非インクリメンタル (non-incremental) モードの
2 つがあります。
イ ンクリメンタル検索は、ユーザが検索文字列の入力を終えるより前に検索を
開始します。検索文字列に文字が追加されるたびに、 readline は現在まで 入
力 した文字列にマッチする履歴から次のエントリを表示します。インクリメン
タル検索で必要なのは、探している履歴エントリを見つけるために必要な数 の
文 字 だけです。インクリメンタル検索を終了させるには、 isearch-termina-
tors の値に入っている文字を使います。この変数に値が代入されていない場合
には、エスケープ文字または Control-J でインクリメンタル検索が終了します
。 Control-G はインクリメンタル検索を異常終了させ、元の行を復元します。
検索が終了すると、検索文字列を含む履歴エントリが現在の行になります。
マッチした他の履歴リストのエントリを見つけるには、Control-S または Con-
trol-R を適宜入力します。これにより、今まで入力した検索文字列にマッチす
る 次のエントリを履歴の前方または後方に向かって探します。 readline に割
り当てられた他のキーシーケンスを入力すると検索が終わり、そのコマンド が
実 行されます。例えば、改行は検索を終了させて、その行を入力します。これ
により、履歴リスト中のコマンドが実行されます。
インクリメンタルでない検索の場合には、履歴行にマッチするものの検索を 始
め る前に検索する文字列全体を読み込みます。検索文字列には、ユーザが入力
したものか、現在の行の内容の一部を使えます。
Readline のコマンド名
以下に示すのは、コマンドの名前およびそれらが割り当てられているデフォ ル
ト のキーシーケンスの一覧です。対応するキーシーケンスが無いコマンド名に
は、デフォルトではキーは割り当てられていません。以下の説明では、ポイ ン
ト (point) は現在のカーソルの位置を表し、マーク (mark) は set-mark コマ
ンドによって保存されたカーソル位置を表します。ポイントとマークの間の テ
キストは、リージョン (region) で表します。
移動コマンド
beginning-of-line (C-a)
現在の行の先頭に移動します。
end-of-line (C-e)
行の末尾に移動します。
forward-char (C-f)
1 文字進みます。
backward-char (C-b)
1 文字戻ります。
forward-word (M-f)
次の単語の最後に進みます。単語は英数字 (文字と数字) からなります
。
backward-word (M-b)
現在の単語あるいは前の単語の先頭に戻ります。単語は英数字 (文字と
数字) からなります。
clear-screen (C-l)
現在の行を画面の一番上の行に残したまま、画面をクリアします。引き
数を付けると、画面をクリアせずに現在の行を再描画します。
redraw-current-line
現在の行を再描画します。
履歴操作のためのコマンド
accept-line (Newline, Return)
カーソルの位置に関わらず、行を入力します。この行が空でなければ、
変 数 HISTCONTROL の状態に従って、これが履歴リストに追加されます
。行が履歴リストを変更したものならば、履歴行は元の状態に戻されま
す。
previous-history (C-p)
履歴リストを戻り、履歴リストから前の行を取り出します。
next-history (C-n)
履歴リストを進み、履歴リストから次の行を取り出します。
beginning-of-history (M-<)
履歴の最初の行に移動します。
end-of-history (M->)
入力履歴の最後に移動します。つまり、現在入力中の行に移動します。
reverse-search-history (C-r)
現在の行を開始点にして後方に向かって検索を行い、必要に応じて履歴
を「遡って」いきます。これはインクリメンタル検索です。
forward-search-history (C-s)
現在の行を開始点にして前方に向かって検索を行い、必要に応じて履歴
を「下って」いきます。これはインクリメンタル検索です。
non-incremental-reverse-search-history (M-p)
現在の行を開始点にして、履歴リストを後方に向かって検索を行います
。この際には、ユーザが入力した文字列を非インクリメンタルモードで
検索します。
non-incremental-forward-search-history (M-n)
現在の行を開始点にして、履歴リストを前方に向かって検索を行います
。この際には、ユーザが入力した文字列を非インクリメンタルモードで
検索します。
history-search-forward
履歴を前方に向かって検索し、現在の行の先頭とポイントの間の文字列
を探します。これは非インクリメンタル検索です。
history-search-backward
履歴を後方に向かって検索し、現在の行の先頭およびポイントの間の文
字列を探します。これは非インクリメンタル検索です。
yank-nth-arg (M-C-y)
前のコマンドに対する最初の引き数 (通常は前の行の 2 番目の 単 語)
を ポイントに挿入します。引き数 n が付いていると、前のコマンドの
n 番目の単語 (前のコマンドの単語は 0 から数えます)。引き数が負な
らば、前のコマンドの最後から n 番目の単語が挿入されます。
yank-last-arg (M-., M-_)
前のコマンドの最後の引き数 (一つ前の履歴エントリの最後の単語) を
挿入します。引き数があると、yank-nth-arg と全く同じように動作 し
ま す。 yank-last-arg を繰り返して呼び出すと、履歴リストを遡って
参照が行われ、それぞれの行の最後の引き数が順番に挿入されます。
shell-expand-line (M-C-e)
シェルのように行を展開します。エイリアスや履歴の展開など、シェル
の 行う単語展開を行います。履歴の展開の説明については、後述の 履
歴の展開を参照してください。
history-expand-line (M-^)
現在の行で履歴の展開を行います。履歴の展開の説明については、後述
の 履歴の展開を参照してください。
magic-space
現在の行で履歴の展開を行い、空白を挿入します。履歴の展開の説明に
ついては、後述の 履歴の展開を参照してください。
alias-expand-line
現在の行でエイリアスの展開を行います。エイリアスの展開の説明につ
いては、前述の エイリアスを参照してください。
history-and-alias-expand-line
現在の行で履歴とエイリアスの展開を行います。
insert-last-argument (M-., M-_)
yank-last-arg と同じものです。
operate-and-get-next (C-o)
現在の行を実行し、現在の行の次の行を編集するために履歴から取得し
ます。引き数は全て無視されます。
テキスト編集のためのコマンド
delete-char (C-d)
ポイントの文字を削除します。ポイントが行の先頭であり、その行に文
字 が無く、さらに打ち込んだ最後の文字が delete-char に割り当てら
れていなければ、 EOF が返されます。
backward-delete-char (Rubout)
カーソルの前の文字を削除します。数値の引き数を与えると、削除した
テキストをキルリングに保存します。
forward-backward-delete-char
カーソルが行末になければカーソルがある位置の文字を削除します。カ
ーソルが行末にある場合には、カーソルの前の文字を削除します。デフ
ォルトでは、これはキーに割り当てられていません。
quoted-insert (C-q, C-v)
次 に打ち込んだ文字をそのまま行に追加します。これは C-q 等の文字
を挿入するために使います。
tab-insert (C-v TAB)
タブ文字を挿入します。
self-insert (a, b, A, 1, !, ...)
打ち込んだ文字を挿入します。
transpose-chars (C-t)
ポイントの前にある文字を動かし、現在ポイントがある文字の後ろに持
っていきます。同時にポイントも前に進みます。ポイントが行の最後に
ある場合は、ポイントの前の 2 文字が交換されます。負の引き数を 指
定すると、何も起こりません。
transpose-words (M-t)
ポイントの前にある単語を動かし、ポイントの後ろにある単語の後ろに
持っていきます。この際には、ポイントも始めに前にあった単語の後ろ
まで移動します。
upcase-word (M-u)
現在の (または後ろの) 単語を大文字にします。負の引き数を指定する
と、前の単語を大文字にしますが、ポイントは動きません。
downcase-word (M-l)
現在の (または後ろの) 単語を小文字にします。負の引き数を指定する
と、前の単語を小文字にしますが、ポイントは動きません。
capitalize-word (M-c)
現在の (または後ろの) 単語をキャピタライズします (単語の先頭の文
字を大文字にします)。負の引き数を指定すると前の単語をキャピタ ラ
イズしますが、ポイントは動きません。
キルとヤンク
kill-line (C-k)
ポイントから行末までのテキストをキルします。
backward-kill-line (C-x Rubout)
現在のカーソル位置から行頭までをキルします。
unix-line-discard (C-u)
ポイントから行頭までをキルします。キルされたテキストはキルリング
(kill-ring) に入ります。
kill-whole-line
現在の行の文字を全てキルします。ポイントの位置は関係ありません。
kill-word (M-d)
ポイントから現在の単語の終わりまでをキルします。ポイントが単語と
単語の間であれば、後ろの単語の終わりまでをキルします。単語の境界
は forward-word で使われているものと同じです。
backward-kill-word (M-Rubout)
ポ イ ントの下にある単語をキルします。単語の境界は backward-word
で使われているものと同じです。
unix-word-rubout (C-w)
ポイントの下にある単語をキルします。その際には空白を単語の境界と
して用います。キルされたテキストはキルリングに入ります。
delete-horizontal-space (M-\)
ポイントの周りの空白とタブを全て削除します。
kill-region
現在のリージョン中のテキストをキルします。
copy-region-as-kill
リージョン中のテキストをキルバッファにコピーします。
copy-backward-word
ポ イ ン ト の前の単語をキルバッファにコピーします。単語の境界は
backward-word と同じです。
copy-forward-word
ポイントの後ろの単語をキルバッファにコピーします。単語の境 界 は
forward-word と同じです。
yank (C-y)
キルリングの先頭のテキストをポイントのあるバッファにヤンクします
。
yank-pop (M-y)
キルリングをローテートし、新たに先頭になったテキストをヤンクしま
す。 yank または yank-pop の後にしか使えません。
数値の引き数
digit-argument (M-0, M-1, ..., M--)
既に蓄積中の引き数にこの数字を追加するか、またはこの数字によって
新しい引き数を始めます。 M-- を使うと、負の値を指定できます。
universal-argument
引き数を指定する別法です。このコマンドの後に 1 つ以上の数字が あ
る 場合 (頭にマイナス記号を付けることもできます)、これらの数字で
引き数が定義されます。コマンドの後に数字を続けた場合 、 univer-
sal-argument を再び実行すると数値の引き数を終了しますが、そうで
ない場合は無視されます。特殊なケースとして、このコマンドの直後に
数字でもマイナス記号でもない文字がある場合には、次のコマンドの引
き数カウントは 4 倍にされます。最初は引き数カウントは 1 なので、
こ の機能を一度実行すると引き数カウントは 4 になり、次に実行する
と引き数カウントは 16 になります。それ以降も同様です。
補完
complete (TAB)
ポイントの前のテキストについて補完を試みます。 bash が補完を行う
際にはテキストの扱いの種類を順に試しますが、その順序は、変数 (テ
キストが $ で始まる場合)、ユーザ名 (テキストが ~ で始まる場合)、
ホスト名 (テキストが @ で始まる場合)、コマンド (エイリアスや関数
も含みます) です。これらのうちいずれにもマッチしない場合には、フ
ァイル名補完を試みます。
possible-completions (M-?)
ポイントの前のテキストを補完して得られるものの候補を列挙します。
insert-completions (M-*)
ポイントの前のテキストを補完して得られるものを全て挿入します。挿
入 されるものは、possible-completions で列挙されるものと同じです
。
menu-complete
complete コマンドに似ていますが、補完される単語を補完候補リス ト
のうちの 1 つと置換します。 menu-complete を繰り返して実行すると
、補完の候補リストが次々と順番に挿入されます。補完リストの最後ま
で 来るとベルが (bell-style の設定に基づいて) 鳴らされ、元のテキ
ストに戻ります。引き数 n を指定すると、リスト中の位置が n 個進み
ます。負の引き数を指定すると、リスト中を逆向きに戻れます。このコ
マンドは TAB に割り当てることを意図して用意されたものですが、 デ
フォルトでは割り当ては行われていません。
delete-char-or-list
カ ー ソルが行頭や行末に無ければ、カーソルの下の文字を削除します
(delete-char と同様です)。カーソルが行末にある場合 は 、 possi-
ble-completions と同じ動作をします。このコマンドはデフォルトでは
キーに割り当てられていません。
complete-filename (M-/)
ポイントの前のテキストについて、ファイル名の補完を試みます。
possible-filename-completions (C-x /)
ポイントの前のテキストについて、補完の候補を列挙します。テキスト
はファイル名として扱います。
complete-username (M-~)
ポイントの前のテキストについて補完を試みます。テキストはユーザ名
として扱います。
possible-username-completions (C-x ~)
ポイントの前のテキストについて補完の候補を列挙します。テキストは
ユーザ名として扱います。
complete-variable (M-$)
ポイントの前のテキストについて補完を試みます。テキストはシェル変
数として扱います。
possible-variable-completions (C-x $)
ポイントの前のテキストについて補完の候補を列挙します。テキストは
シェル変数として扱います。
complete-hostname (M-@)
ポイントの前のテキストについて補完を試みます。テキストはホスト名
として扱います。
possible-hostname-completions (C-x @)
ポイントの前のテキストについて補完の候補を列挙します。テキストは
ホスト名として扱います。
complete-command (M-!)
ポイントの前のテキストについて補完を試みます。テキストはコマンド
名として扱います。コマンド補完の際にマッチングを試みる順序は、エ
イリアス、予約語、シェル関数、シェルの組み込みコマンド、実行ファ
イルです。
possible-command-completions (C-x !)
ポイントの前のテキストについて補完の候補を列挙します。テキストは
コマンド名として扱います。
dynamic-complete-history (M-TAB)
ポイントの前のテキストについて補完を試みます。テキストの比較が行
われるのは、履歴リスト中の行のうち補完の候補となるものです。
complete-into-braces (M-{)
ファイル名補完を実行し、補完の候補リストを挿入します。シェルから
利用可能なリストとなるように、返される候補はブレースで括られます
(前述の ブレース展開を参照)。
キーボードマクロ
start-kbd-macro (C-x ()
現在のキーボードマクロに対して入力される文字列の保存を開始します
。
end-kbd-macro (C-x ))
現在のキーボードマクロに対して入力された文字列の保存を終了し、こ
の定義を格納します。
call-last-kbd-macro (C-x e)
最後に定義されたキーボードマクロを再実行します。再実行は、マクロ
中の文字列をキーボードでの入力と同様に出力することによって行いま
す。
その他
re-read-init-file (C-x C-r)
inputrc ファイルの内容を読み込み、このファイル中の割り当てや変数
設定を取り込みます。
abort (C-g)
現 在 の 編 集 行 を 捨 て 、 端末のベルを鳴らします (この動作は
bell-style の設定に従って行います)。
do-uppercase-version (M-a, M-b, M-x, ...)
メタ文字と共に入力された文字 x が小文字であれば、これに対応す る
大文字に割り当てられているコマンドを実行します。
prefix-meta (ESC)
次に入力される文字を、メタプレフィックスされたことにします。 ESC
f は Meta-f と同じ意味です。
undo (C-_, C-x C-u)
インクリメンタルアンドゥを行います。これは行ごとに別々に記憶され
ています。
revert-line (M-r)
この行に対して行った変更を全て取り消します。このコマンドは、行が
初期状態に戻るまで undo コマンドを実行するようなものです。
tilde-expand (M-&)
現在の単語についてチルダ展開を実行します。
set-mark (C-@, M-)
ポイントにマークを設定します。数字の引き数が与えられた場合には、
マークにはその位置が設定されます。
exchange-point-and-mark (C-x C-x)
ポイントをマークと入れ換えます。現在のカーソル位置は保存されてい
る位置となり、古いカーソル位置がマークとして保存されます。
character-search (C-])
文字を 1 つ読み込み、その文字が次に現われる場所にポイントを移 動
させます。負のカウントを与えると、その文字が前に現われた場所を探
します。
character-search-backward (M-C-])
文字を 1 つ読み込み、その文字が前に現われた場所にポイントを移 動
させます。負のカウントを与えると、その文字が次に現われる場所を探
します。
insert-comment (M-#)
まず readline の comment-begin 変数の値が現在の行の先頭に挿入 さ
れ 、 次に改行が打ち込まれたのと同じように行の入力が行われます。
comment-begin のデフォルト値によって、このコマンドは現在の行をシ
ェルのコメントとします。
glob-expand-word (C-x *)
ポイントの前の単語がパス名展開のパターンとして扱われ、この単語と
置き換えられる形でマッチするファイル名のリストが挿入されます。
glob-list-expansions (C-x g)
glob-expand-word で生成されるのと同じ展開結果のリストが表示さ れ
、行が再描画されます。
dump-functions
機能とそのキー割り当てを全て、 readline の出力ストリームに出力し
ます。数値の引き数を与えると、出力は inputrc に書き込める形に 整
形されます。
dump-variables
設定可能な readline の変数とその値を全て readline の出力ストリー
ムに出力します。数値の引き数を与えると、出力は inputrc に書き 込
める形に整形されます。
dump-macros
マクロとマクロが出力する文字列に割り当てられた readline のキーシ
ーケンスを全て出力します。数値の引き数を与えると、出力は inputrc
に書き込める形に整形されます。
display-shell-version (C-x C-v)
現在実行している bash のバージョン情報を表示します。
プログラム補完
complete 組み込みコマンドで補完仕様 (compspec) が定義されているコマンド
に対して引き数の単語補完が試みられると、プログラム可能な補完の機能が 呼
び 出されます (complete 組み込みコマンドについては、後述する シェルの組
み込みコマンドを参照)。
まず、コマンド名が特定されます。そのコマンドに対して補完仕様が定義さ れ
て いれば、それがその単語の補完候補のリスト作成に使われます。コマンドの
単語がフルパス名であれば、最初にフルパス名の補完仕様が検索されます。 フ
ル パス名の補完仕様が見つからなかった場合は、最後のスラッシュ以降の部分
に対して該当する補完仕様を見つけようとします。
補完仕様が見つかると、それはマッチする単語のリストを作成するために使 用
さ れます。補完仕様が見つからなかった場合は、前述の 補完 で説明したよう
なデフォルトの bash の補完が行われます。
まず、補完仕様で指定された動作が用いられます。補完される単語の前置部 分
にマッチするものだけが返されます。ファイル名やディレクトリ名の補完に -f
や -d オプションが使用された場合は、シェル変数 FIGNORE がマッチのフィル
タとして使用されます。
続 いて -G オプションによって指定されたファイル名展開パターンの補完が生
成されます。パターンによって生成された単語は、補完される単語とマッチ す
る 必要はありません。 GLOBIGNORE シェル変数はマッチのフィルタとしては使
われませんが、 FIGNORE 変数は使用されます。
次に、 -W オプションで指定された引き数の文字列が考慮されます。文字列 は
、最初に IFS 特殊変数の文字を区切り文字として分割されます。シェルのクォ
ート処理は考慮されます。それぞれの単語は、前述の 展開で示したように、ブ
レ ース展開、チルダ展開、パラメータと変数の展開、コマンド置換、算術式展
開、パス名展開が行われます。結果は、前述の単語の分割で示した規則によ っ
て 分割されます。展開の結果は補完される単語の前置部分とマッチが行われ、
マッチした単語が補完候補となります。
これらのマッチが生成された後、シェル関数や -F や -C オプションで指定 さ
れ た コ マ ン ドが呼び出されます。コマンドや関数が呼び出されるときは、
COMP_LINE と COMP_POINT 変数に後述のシェル変数で示すように値が設定さ れ
ま す。シェル関数が呼び出される場合は、 COMP_WORDS と COMP_CWORD 変数も
設定されます。関数やコマンドが呼び出されるときは、最初の引き数は引き 数
が 補完されるコマンドの名前、二番目の引き数は補完される単語、三番目の引
き数は現在のコマンドラインで補完中の単語の前に置かれる単語となります 。
補 完される単語に対して生成された補完の候補はフィルタリングされません。
関数やコマンドは生成されたマッチとは無関係に補完されます。
-F で指定された関数がまず呼び出されます。関数は、後述する compgen 組 み
込 みコマンドを含めた、全てのシェルの機能を使ってマッチを生成します。補
完候補は必ず COMPREPLY 配列変数に格納されます。
続いて -C オプションで指定されたコマンドが呼び出され、環境変数をコマ ン
ド置換します。このコマンドは、補完候補を 1 行にひとつずつ標準出力に出力
します。必要があれば、バックスラッシュが改行をエスケープするために使 用
されます。
全 ての補完候補が生成された後で、 -X オプションで指定されたフィルタが補
完候補に作用します。フィルタは、パス名展開で使用されたようなパターン で
す 。パターン中の & は補完される単語に置換されます。文字通りの & はバッ
クスラッシュでエスケープします。バックスラッシュはマッチを試みる前に 削
除 されます。パターンにマッチした補完は候補から削除されます。先行する !
はパターンを否定します。この場合、パターンにマッチしなかった補完が削 除
されます。
最後に、-P と -S オプションで指定された前置部分と後置部分が補完候補のそ
れぞれに加えられます。そして結果が readline 補完コードに補完候補のリ ス
トとして返されます。
直 前 に 行 われた動作が何にもマッチせず、補完仕様が定義されたときに -o
dirname オプションが complete に与えられていれば、ディレクトリ名への 補
完が試みられます。
デ フォルトでは、補完仕様が見つかった場合、それが生成したものがなんであ
れ、可能性のある補完すべてのリストとして、補完コードに返されます。デ フ
ォ ルトの bash 補完は試みられず、 readline のデフォルトのファイル名補完
は無効になります。補完仕様の定義時に -o default オプション が complete
に 与えられていれば、補完仕様が何にもマッチしなければ readline のデフォ
ルトの補完が行われます。
履歴 (HISTORY)
-o history オプションを組み込みコマンドの set で有効にすると、コマン ド
履 歴 (command history) (以前に入力したコマンドのリスト) にアクセスでき
るようになります。変数 HISTSIZE の値が、履歴リストに保存するコマンド の
数 になります。過去に入力したコマンドのうち、最新 HISTSIZE 個分 (デフォ
ルトは 500 個) のテキストが保存されます。シェルは各コマンドを、パラメー
タ展開や変数展開 (前述の 展開を参照) を行う前のかたちで履歴リストに格納
します。ただし、履歴展開は実行してから格納します。履歴展開はシェル変 数
HISTIGNORE と HISTCONTROL の値に従って実行されます。
起 動時に、履歴は HISTFILE 変数 (デフォルトは ~/.bash_history) が示すフ
ァイルの内容で初期化されます。 HISTFILE で指定されたファイルは、 HIST-
FILESIZE で指定された行数を越えないように、必要に応じて切り詰められます
。対話的なシェルが終了する際には、最近の HISTSIZE 個の行が履歴リスト か
ら HISTFILE にコピーされます。シェルオプションの histappend ( シェルの
組み込みコマンドの項の shopt の説明を参照) が有効になっていると、これら
の 行は履歴ファイルの末尾に追加されます。このオプションが無効ならば、履
歴ファイルは上書きされます。 HISTFILE が設定されていないか、履歴ファ イ
ル が書き込めない状態だと、履歴は保存されません。履歴の保存を行った後に
は、履歴ファイルは行数が HISTFILESIZE 行を越えないように切り詰められ ま
す。 HISTFILESIZE が設定されていなければ、切り詰めは行われません。
組 み込みコマンド fc (後述の シェルの組み込みコマンドを参照) を用いると
、履歴リストの一部をリスト・編集して再実行できます。組み込みコマンド の
history を用いると、履歴リストを表示・編集したり、履歴ファイルを操作で
きます。コマンドラインを編集する際には、各編集モードでいろいろな検索 コ
マンドが利用でき、履歴リストへアクセスできます。
こ のシェルでは、どのコマンドが履歴リストに保存されるかを制御できます。
HISTCONTROL 変数と HISTIGNORE 変数を設定すると、シェルは入力されたコ マ
ンドの一部しか保存しなくなります。シェルオプションの cmdhist を有効にす
ると、シェルは複数行に別れているコマンドの各行を同じ履歴エントリに保 存
し ようとします。この際には、文法的な正しさを保つためにセミコロンが必要
に応じて追加されます。シェルオプションの lithist を有効にすると、このシ
ェ ルは行の途中にセミコロンではなく改行文字を置く形でコマンドを保存しま
す。シェルオプションの設定と設定取り消しについては、後述の シェルの組み
込みコマンドにおける説明を参照してください。
履歴の展開
このシェルは、 csh の履歴展開と同じような機能をサポートしています。この
セクションでは、履歴展開で使用できる記法・機能を説明します。この機能 は
対 話 的 シェルならばデフォルトで有効になっていますが、組み込みコマンド
set の +H オプション (後述の シェルの組み込みコマンドを参照) で無効にで
きます。非対話的シェルの場合は、デフォルトでは履歴展開は行われません。
履 歴展開は、履歴リスト中の単語を入力ストリームに入れます。この機能を利
用すると、コマンドを繰り返したり、前のコマンドで指定したオプションを 現
在 の入力行に挿入したり、前のコマンドの誤りを手早く直したり、といったこ
とが簡単にできるようになります。
履歴展開が実行されるのは入力行全体を読み込んだ直後であり、シェルが行 を
単語に分割するよりも前です。履歴展開の動作は 2 段階で行われます。まず最
初に、置換に使う行を履歴リストから選びます。次に、その行のどの部分を 現
在 の 行 に 書 き込むかを選択します。履歴リストから選ばれた行はイベント
(event) と呼ばれ、この行のうち動作の対象となる部分を単語列 (words)と 呼
び ます。様々な修飾子 (modifier) が利用でき、選択された単語列の操作が可
能になっています。行の単語への分割は入力を読み込む時と同じように行わ れ
るので、メタ文字で区切られた複数の単語をクォートで括ったものは 1 つの単
語と見なされます。履歴展開が行われるのは、履歴展開文字が現われた時で す
。履歴展開文字はデフォルトでは ! です。履歴展開文字をクォートできるのは
、バックスラッシュ (\) とシングルクォートだけです。
組み込みコマンドの shopt を用いて、何種類かあるシェルオプションを設定す
る と、履歴展開の動作を調整できます。シェルオプションの histverify が有
効で (組み込みコマンド shopt の説明を参照)、かつ readline が使われて い
る 場合には、履歴置換を行った結果はすぐにはシェルのパーザに渡されません
。展開された行は readline の編集バッファに再び読み込まれ、さらに編集 が
行 える状態になります。 readline を使用しており、かつシェルオプションの
histreedit が有効である場合、履歴置換が失敗してもその結果は readline の
編 集バッファに再び読み込まれ、訂正できる状態となります。組み込みコマン
ド history の -p オプションを使うと、実際に履歴展開を行う前に、どのよう
に展開されるのかを見ることができます。組み込みコマンド history の -s オ
プションを使うと、コマンドを履歴リストの末尾に (実際の実行はせずに) 追
加できます。追加したコマンドは、後で再呼び出しできます。
このシェルでは、履歴展開機構で使ういろいろな文字を制御できます (前述の
シェル変数の項目における histchars の説明を参照)。
イベント指示子 (Event Designator)
イベント指示子は、履歴リスト中のコマンドラインエントリを参照するもの で
す。
! 履歴置換を開始します。ただし、ブランク文字、改行文字、=, ( のい
ずれかが後に続く場合は除きます。
!n n 行目のコマンドラインを参照します。
!-n 現在から n 行前のコマンドラインを参照します。
!! 1 行前のコマンドラインを参照します。‘!-1’ と同義です。
!string
string で始まるコマンドのうち、一番現在に近いところで実行した も
のを参照します。
!?string[?]
string を含むコマンドのうち、一番現在に近いところで実行したもの
を参照します。 string の直後が改行文字ならば、最後の ? は省略 し
ても構いません。
^string1^string2^
簡易置換。 string1 を string2 に置換して直前のコマンドを繰り返し
ます。 ‘‘!!:s/string1/string2/’’ と同義です (後述の修飾子を参照)
。
!# 今までのところまでに打ち込んだコマンドライン全体です。
単語指示子 (Word Designators)
単語指示子 (word designator) は、イベントから欲しい単語を選ぶ時に用いら
れます。イベント指定と単語指示子のセパレータには : を用います。単語指示
子が ^, $, *, -, % のいずれかで始まる場合には、このセパレータは省略でき
ます。単語には行の先頭から番号が振られます。先頭の単語が 0 番目になりま
す。単語は現在の行に、空白 1 つで区切られて挿入されます。
0 (ゼロ)
0 番目の単語。このシェルにとっては、これはコマンドを表す単語です
。
n n 番目の単語。
^ 最初の引き数。つまり 1 番目の単語です。
$ 最後の引き数。
% ‘?string?’ 検索にマッチする、一番現在に近い単語。
x-y 単語の範囲。‘0-y’ の省略形として ‘-y’ が使えます。
* 0 番目を除く全ての単語。これは ‘1-$’ の別表現です。イベント中 に
1 つしか単語が現われないときに * を使ってもエラーにはなりません
。このような場合には空文字列が返されます。
x* x-$ の省略形です。
x- x* と同様に x-$ の省略形ですが、ただし最後の単語は含みません。
イベント指定なしに単語指示子が与えられた場合、直前のコマンドがイベン ト
として使われます。
修飾子 (Modifiers)
単 語指示子 (省略可能) の後には、以下に示す修飾子を、1 個以上のシーケン
スのかたちで置けます。それぞれの修飾子の前には ‘:’ をつけます。
h パス名から末尾にある部分 (ファイル名) を取り除き、前の方 (ディレ
クトリ部) だけを残します。
t パス名から前の方 (ディレクトリ部) を取り除き、末尾にある部分 (フ
ァイル名) だけを残します。
r 末尾にある .xxx 形式のサフィックスを取り除き、ベー ス 名 (base-
name) だけを残します。
e 末尾のサフィックスだけを残して、全ての部分を取り除きます。
p 新しいコマンドを表示しますが、実行はしません。
q 置換が行われた単語をクォートし、それ以上の置換が行われないように
します。
x q と同じように置換後の単語をクォートしますが、 空白文字と改行 文
字のところで単語に分割します。
s/old/new/
イベント行で最初に現われた old を new に置き換えます。/ の代わり
に任意の区切り文字を使うこともできます。最後の区切り文字がイベン
ト行の最後の文字ならば、これは省略できます。 old と new の中では
、バックスラッシュ 1 つでクォートすれば区切り文字も使え ま す 。
new に & が含まれている場合には、これは old に置き換えられます。
バックスラッシュ 1 つを前に置けば & をクォートできます。 old が
空 文字列ならば、これには前回に置換された old が設定されます。以
前に履歴置換が全く行われていない場合には 、 現 在 に 一 番 近 い
!?string[?] の検索で使われた string が設定されます。
& 直前の置換を繰り返します。
g 変更をイベント行全体に適用します。これは ‘:s’ と組み合わせて使わ
れます (例:‘:gs/old/new/’)。 ‘:s’ と一緒に使った場合には、 / の
代わりに任意の区切り文字を使えます。また最後の区切り文字がイベン
ト行の最後の文字ならば、これは省略できます。
シェルの組み込みコマンド
特に断らない限り、このセクションで説明されている組み込みコマンドのう ち
- で始まるオプションを受け付けるものは、オプションの終わりを表す -- も
受け付けます。
: [arguments]
何もしません。このコマンドは arguments を展開し、指定されたリ ダ
イ レクトを実行する以外には何も行いません。終了コード 0 を返しま
す。
. filename [arguments]
source filename [arguments]
filename からコマンドを読み込み、現在のシェル環境のもとで実行 し
ます。そして filename 中で最後に実行したコマンドの終了ステータス
を返します。 filename にスラッシュが含まれていない場合 、 file-
name は PATH に含まれるディレクトリから探されます。 PATH 内で検
索されるファイルは、実行可能である必要はありません 。 bash が
posix モードで動作していなければ、 PATH 中でファイルを見つけられ
なかった場合には、カレントディレクトリが検索されます。組み込みコ
マ ンド shopt に対する sourcepath オプションが無効にされている場
合、 PATH の検索は行われません。何らかの arguments が与えられ て
いる場合、これらの引き数は filename を実行した時の位置パラメータ
となります。そうでない場合は、位置パラメータは変更されません。返
却ステータスはスクリプト内で最後に実行したコマンドのステータスで
す (コマンドが全く実行されなければ 0 です)。また filename が見つ
からない場合や読み込めない場合には偽となります。
alias [-p] [name[=value] ...]
alias コマンドを引き数を付けずに (あるいは -p オプションを付け
て) 実行すると、エイリアスのリストが「alias name=value」の形で標
準出力に出力されます。引き数を与えた場合には、value を与えられた
name それぞれに対するエイリアスが定義されます。 value の末尾に空
白があると、エイリアスが展開された時に、空白の次の単語についてエ
イリアス置換があるかどうか調べられます。引き数リスト中 に value
が与えられていない name があった場合は、それぞれに対して名前とエ
イリアスの値が出力されます。エイリアスが定義されていない name が
与えられなければ、 alias は真を返します。
bg [jobspec]
サ スペンドされているジョブ jobspec をバックグラウンドで実行再開
します。このジョブは、初めから & を付けて起動されていたかのよ う
に 動作を続けます。 jobspec が無い場合には、シェルが記録している
カレントジョブ (current job) が使われます。 bg jobspec は通常 0
を返しますが、ジョブ制御が無効であるときに実行した場合や、ジョブ
制御が有効であっても jobspec が有効なジョブを指定していない場 合
や jobspec がジョブ制御無しで実行したジョブを指定している場合は
異なる値を返します。
bind [-m keymap] [-lpsvPSV]
bind [-m keymap] -x keyseq:shell-command
bind [-m keymap] [-q function] [-u function] [-r keyseq]
bind [-m keymap] -f filename
bind [-m keymap] keyseq:function-name
readline の現在のキー割り当てと関数割り当てを表示します。ある い
はキーシーケンスを readline の関数やマクロに割り当てます。受け付
ける割り当ての記法は .inputrc と全く同じですが、それぞれの割り当
て は 別 々 の 引 き 数 と し て 渡 さなければなりません。例えば
’"\C-x\C-r": re-read-init-file’ のように指定します。オプションを
指定した場合には、以下のような意味を持ちます:
-m keymap
キ ーマップ keymap を、以降の割り当てによって変更します。
指 定 で き る keymap 名 は 、emacs, emacs-standard,
emacs-meta, emacs-ctlx, vi, vi-move, vi-command,
vi-insert です。 vi は vi-command と同じです。また emacs
は emacs-standard と同じです。
-l readline 関数の名前を全てリスト表示します。
-p readline の関数の名前と割り当てを表示します。表示は、再び
読み込みできる形式で出力されます。
-P readline の関数の現在の名前と割り当てをリスト表示します。
-v readline の変数名と値を表示します。表示は、再び読み込みで
きる形式で出力されます。
-V readline の現在の変数名と値をリスト表示します。
-s readline のマクロに割り当てられたキーシーケンスと、マクロ
が 出力する文字列を表示します。表示は、再び読み込みできる
形式で出力されます。
-S readline のマクロに割り当てられたキーシーケンスと、マクロ
が出力する文字列を表示します。
-f filename
キー割り当てを filename から読み込みます。
-q function
指定された function を呼び出すキーを問い合わせます。
-u function
指 定された function に割り当てられているキーの割り当てを
全て取り消します。
-r keyseq
keyseq に対する現在の割り当てを削除します。
-x keyseq:shell-command
keyseq が押されるたびごとに、 shell-command が実行され る
ようにします。
認識できないオプションが与えられた場合やエラーが起きた場合を除け
ば、返り値は 0 です。
break [n]
for, while, until, select のループから抜けます。n が指定されてい
れ ば、n レベル分 break します。 n は 1 以上でなければなりません
。 n がループの深さよりも大きい場合には、全てのループから抜け ま
す 。 n が 0 以下なら、返り値は 0 以外の値となります。さもなけれ
ば、 break は 0 を返します。
builtin shell-builtin [arguments]
指定されたシェル組み込みコマンドを実行します。コマンドには argu-
ments を引き数として渡し、このコマンドの終了ステータスを返します
。これはシェル組み込みコマンドと同じ名前の関数を定義する時に便利
で、その関数内で組み込みコマンドを使った時に、その機能を損ないま
せん。組み込みコマンド cd は普通、これを使って再定義されま す 。
shell-builtin がシェル組み込みコマンドでなければ、終了ステータス
は偽となります。
cd [-LP] [dir]
カレントディレクトリを dir に変更します。変数 HOME の値が dir の
デ フォルト値です。変数 CDPATH は、 dir を含むディレクトリの検索
パスを定義します。 CDPATH 内ではディレクトリ名はコロン (:) で 区
切ります。 CDPATH 中に空のディレクトリ名がある場合、これはカレン
トディレクトリ (つまり ‘‘.’’) を意味します。 dir がスラ ッ シ ュ
(/) で始まる場合には、 CDPATH は使われません。 -P オプションは、
シンボリックリンクを辿らないで物理的なディレクトリ構造を使うよう
に 指示します (組み込みコマンド set の -P オプションも参照)。 -L
オプションを指定すると、シンボリックリンクを辿るようになります。
引き数に - を指定するのは、 $OLDPWD を指定するのと同じ意味です。
ディレクトリの変更が成功した場合には返り値は真になります。そうで
ない場合には偽になります。
command [-pVv] command [arg ...]
command に引き数 args を付けて実行します。シェル関数の通常の参照
は行いません。組み込みコマンドと PATH 内で見つかるコマンドだけが
実 行されます。 -p オプションが与えられると、 command の検索を行
う際に PATH のデフォルト値が使われます。これにより、標準ユーティ
リティを全て確実に見つけられます。 -V オプションまたは -v オプシ
ョンを与えると、 command の説明が出力されます。 -v オプション で
は 、 command を起動する時に使われるコマンドやファイル名を示す単
語が表示されます。 -V ではさらに詳しい説明が表示されます。 -V オ
プ シ ョンや -v オプションを与えた場合、終了ステータスは command
が見つかれば 0 となり、見つからなければ 1 となります。どちらのオ
プ ションも与えなかった場合に、エラーが起きたり command を見つけ
られなかったりすると、終了ステータスは 127 になります。それ以 外
の 場 合には、組み込みコマンド command の終了ステータスは、 com-
mand の終了ステータスです。
compgen [option] [word]
option にしたがって、word の補完マッチのリストを生成します。オプ
ションには complete 組み込みコマンドと同じものが指定できますが、
-p と -r は指定できません。マッチのリストは標準出力に出力され ま
す。 -F や -C オプションを使用したときは、プログラム補完機能によ
って設定されたさまざまなシェル変数は、利用可能であっても有用な値
を持ちません。
マッチは、同じフラグで指定されたプログラム補完コードが直接補完を
生成するのと同じ方法で生成されます。 word が指定される と 、word
にマッチする補完だけが表示されます。
戻り値は、無効なオプションが指定された場合やマッチが生成されなか
った場合以外は真になります。
complete [-abcdefjkvu] [-o comp-option] [-A action] [-G globpat] [-W
wordlist] [-P prefix] [-S suffix]
[-X filterpat] [-F function] [-C command] name [name ...]
complete -pr [name ...]
name 引き数それぞれを、どのように補完するのかを指定します 。 -p
オプションが指定された場合や、何もオプションが指定されなかった場
合は、既存の補完指定が (入力として再利用できるかたちで) 出力され
ます。 -r オプションは、それぞれの name の補完指定を削除します。
name が指定されなかった場合はすべての補完指定を削除します。
単語補完が試みられたときにこれらの補完指定に加えられる処理は、前
述の プログラム補完 で示しています。
他 の オプションが指定されたときは、以下のような意味を持ちます。
-G, -W, -X オプションの引き数 (必要ならば -P と -S オプション の
場合も) はクォートして、 complete 組み込みコマンドが呼び出される
前に展開されないようにすべきです。
-o comp-option
comp-option は補完仕様の動作をいくつかの点から制御し、単
純 な補完生成以外ができるようにします。 comp-option には
以下のどれかひとつを指定できます。
default 補完仕様がマッチを全く生成しなかった 場 合 に 、
readline のデフォルトの補完を用います。
dirnames
補完仕様がマッチを全く生成しなかった場合に、ディ
レクトリ名を補完しようとします。
filenames
補完仕様がファイル名を生成することを readline に
伝え、 readline がファイル名特有の処理 (ディレク
トリ名にスラッシュを加えたり、末尾の空白を削除し
たり、など) を行えるようにします。シェル関数と共
に用いることを想定しています。
-A action
action は補完対象リストの生成動作で、以下のどれかひと つ
を指定します。
alias エイリアス名。-a でも指定できます。
arrayvar
配列変数名。
binding readline キー割り当て名。
builtin シェル組み込みコマンド名。-b でも指定できます。
command コマンド名。-c でも指定できます。
directory
ディレクトリ名。-d でも指定できます。
disabled
無効にされているシェル組み込みコマンドの名前。
enabled 有効にされているシェル組み込みコマンドの名前。
export エクスポートされたシェル変数の名前。 -e でも指定
できます。
file ファイル名。-f でも指定できます。
function
シェル関数の名前。
helptopic
help 組み込みコマンドで許可されたヘルプトピッ ク
。
hostname
HOSTFILE シェル変数で指定されたファイルから得ら
れたホスト名。
job ジョブ制御が有効であれば、ジョブ名。-j でも指 定
できます。
keyword シェルの予約語。-k でも指定できます。
running ジョブ制御が有効であれば、実行中のジョブ名。
setopt set 組み込みコマンドの -o オプションで有効な引き
数。
shopt shopt 組み込みコマンドで許可されたシェルオプショ
ン名。
signal シグナル名。
stopped ジョブ制御が有効であれば、停止しているジョブ名。
user ユーザ名。-u でも指定できます。
variable
すべてのシェル変数名。-v でも指定できます。
-G globpat
ファイル名展開パターン globpat が展開されて補完対象の リ
ストを生成します。
-W wordlist
wordlist は IFS 特殊変数を区切り文字として分割され、それ
ぞれの分割された単語は展開されます。補完対象は、展開結果
のリストのメンバのうち、補完中の単語がマッチするものです
。
-C command
command がサブシェル環境で実行され、その出力が補完対象と
して使用されます。
-F function
シェル関数 function は現在のシェル環境で実行されます。関
数が終了したときに、補完対象が COMPREPLY 配列変数から 取
得されます。
-X filterpat
filterpat はファイル名展開として使用されるパターンです。
先行するオプション・引き数によって生成された補完対象リス
ト に適用され、 filterpat とマッチするそれぞれの補完がリ
ストから削除されます。 filterpat の前に ! を置くとパター
ンを否定します。この場合、filterpat にマッチしない補完が
削除されます。
-P prefix
他のすべてのオプションが作用したあとに、 prefix がそれぞ
れの補完対象の先頭に追加されます。
-S suffix
他のすべてのオプションが作用したあとに、 prefix がそれぞ
れの補完対象の末尾に追加されます。
不正なオプションが指定された場合、-p と -r 以外のオプシ ョ ン で
name が指定されなかった場合、存在しない name の指定によって補完
が削除されようとした場合、補完の指定の追加に失敗した場合、を除い
ては、返り値は真になります。
continue [n]
for, while, until, select ループの次の繰り返し分から実行を継続し
ます。 n を指定すると、深さを n 個分上がったループで実行を継続し
ま す。 n は 1 以上でなければなりません。 n がループの深さよりも
大きい場合、最後のループ (「トップレベル」のループ) で実行が継続
されます。ループの中で continue が実行された時に、 n が 0 以下な
ら、返り値は 0 以外の値となります。さもなければ、 continue は 0
を返します。ループの外で continue が実行された時には、返り値は 0
となります。
declare [-afFirx] [-p] [name[=value]]
typeset [-afFirx] [-p] [name[=value]]
変数を宣言したり、変数に属性を与えたりします。 name を指定しなけ
れ ば、変数の値が表示されます。 -p オプションを指定すると、 name
それぞれの属性と値が表示されます。 -p を使うと他のオプションは無
視されます。 -F オプションを指定すると、関数定義の表示を止めます
。関数の名前と属性だけが出力されます。 -F オプションを指定すると
、 -f オプションも指定したことになります。以下のオプションを使う
と、指定した属性を持つ変数の出力を制限したり、変数に属性を与えた
りできます:
-a name はそれぞれ配列変数 (前述の 配列を参照) です。
-f 関数名だけを使います。
-i 変数を整数として扱います。変数に値が代入された時に算術式
評価 ( 算術式評価を参照) が実行されます。
-r name を読み込み専用にします。これ以降、代入文を用いて値を
代入したり unset したりできなくなります。
-x name に印を付け、これ以降に実行するコマンドに環境経由でエ
クスポートします。
‘-’ ではなく ‘+’ を使うと属性を消します。ただし例外として、+a を
使 っ て配列変数を破棄することはできません。関数内で使った場合、
local コマンドを使った場合と同様に name はローカルとなります。返
り値は基本的には 0 ですが、不正なオプションに出会った場合、 ‘‘-f
foo=bar’’ を使って関数を定義しようとした場合、読み込み専用の変数
に代入しようとした場合、複合代入構文を使わずに配列変数に値を代入
しようとした場合 (前述の 配列を参照)、name のいずれかが正しい シ
ェル変数名でない場合、読み込み専用変数の読み込み専用属性を無効に
しようとした場合、存在しない関数を -f オプションで表示しようとし
た場合は除きます。
dirs [-clpv] [+n] [-n]
オプションが無いときは、現在記憶しているディレクトリのリストが表
示されます。デフォルトでは、全てのディレクトリ名は空白で区切って
1 行で表示されます。ディレクトリは pushd コマンドによってリスト
に追加されます。 popd コマンドはリストからエントリを削除します。
+n オプション無しで dirs を起動した時に表示されるリストの、
左から数えて n 番目のエントリを表示します。エントリ は 0
から始まります。
-n オプション無しで dirs を起動した時に表示されるリストの、
右から数えて n 番目のエントリを表示します。エントリ は 0
から始まります。
-c 全てのエントリを削除し、ディレクトリスタックをクリアしま
す。
-l 長い形式のリスト表示を行います。デフォルトのリスト表示 フ
ォ ーマットでは、チルダを使ってホームディレクトリを表しま
す。
-p 1 行に 1 エントリの形でディレクトリスタックを出力します。
-v 1 行に 1 エントリの形でディレクトリスタックを出力します。
各エントリの前にはスタック内での番号が表示されます。
不正なオプションが与えられた場合とインデックス n がディレクト リ
スタックの終端を越えている場合を除き、返り値は 0 となります。
disown [-ar] [-h] [jobspec ...]
オ プション無しの場合には、それぞれの jobspec がアクティブなジョ
ブのテーブルから削除されます。 -h オプションが与えられている場合
、 どの jobspec もテーブルから削除されず、シェルが SIGHUP を受け
取ってもそのジョブには SIGHUP が送られないように印が付けられます
。 jobspec がなく、かつ -a オプションも -r オプションも与えられ
ていない場合には、カレントジョブが使われます。 jobspec が与え ら
れていない場合、 -a オプションは全てのジョブを削除するか全てのジ
ョブに印を付けるという意味となります。 jobspec 引き数なし で -r
オプションを指定すると、実行中のジョブだけが操作の対象となります
。 jobspec が不正なジョブを指定していなければ、返り値は 0 となり
ます。
echo [-neE] [arg ...]
arg を空白で区切って出力し、最後に改行を出力します。終了ステータ
スは常に 0 です。 -n が指定された場合、最後の改行は出力されま せ
ん。 -e オプションを指定した場合、以下に示す、バックスラッシュの
エスケープ文字が解釈されるようになります。 -E オプションを指定す
ると、デフォルトでこのようなエスケープ文字が解釈されるシステムで
あっても、エスケープ文字が解釈されないようになります。 xpg_echo
シェルオプションを用いると、 echo がこれらのエスケープ文字を展開
するかどうかのデフォルト動作を動的に決定できます。 echo は -- を
オプションの終わりと解釈しません。 echo は以下のエスケープシーケ
ンスを解釈します:
\a 警告(ベル)
\b バックスペース
\c 行末に改行を付けない
\e エスケープ文字
\f フォームフィード文字
\n 改行
\r 復帰文字
\t 水平タブ
\v 垂直タブ
\\ バックスラッシュ
\0nnn ASCII コードの 8 進値が nnn である文字 (1 文字につき数 字
3 桁)。
\xnnn ASCII コードの 16 進値が nnn である文字 (1 文字につき数字
3 桁)。
enable [-adnps] [-f filename] [name ...]
組み込みコマンドの有効/無効を設定します。シェルは通常はディス ク
コマンドの前に組み込みコマンドを探しますが、組み込みコマンドを無
効にすると、シェルの組み込みコマンドと同じ名前を持つディスクコマ
ンドを、完全なパス名を指定しなくても実行できます。 -n を用いると
、それぞれの name は無効となります。それ以外の場合には、name は
有効となります。例えば、シェル組み込みのものでなく PATH 上にある
test バイナリを使うには ‘‘enable -n test’’. を実行します 。 -f
オプションは新しい組み込みコマンド name を共有オブジェクト file-
name からロードするという意味です。これは動的ロードをサポート し
ているシステムで使えます。 -d オプションは、以前に -f オプション
でロードした組み込みコマンドを削除します。引き数 name が与えられ
なかった場合や、 -p オプションが与えられた場合、シェルの組み込み
コマンドのリストが表示されます。他にオプション引き数が指定されて
いない場合には、有効になっているシェル組み込みコマンド全てからな
るリストが表示されます。 -n を与えると、無効にされている組み込み
コマンドだけが出力されます。 -a を与えると、それぞれ有効かどうか
の表示付きで全ての組み込みコマンドが出力されます。 -s を与えると
、 出力されるのは POSIX の特殊組み込みコマンドだけに制限されます
。 name がシェル組み込みコマンドでない場合と、共有オブジェクトか
らの新しい組み込みコマンドのロードに失敗した場合を除き、返り値は
0 となります。
eval [arg ...]
arg を読み込み、結合して 1 つのコマンドにされます。次にシェル は
このコマンドを読み込んで実行し、その終了ステータスが eval の値と
して返されます。 args が無い場合や空の引き数しかない 場 合 に は
eval は 0 を返します。
exec [-cl] [-a name] [command [arguments]]
command が指定されていると、シェルはこのコマンドに置き換えられま
す。新しいプロセスは生成されません。 arguments は command に対す
る 引 き数となります。 -l オプションを与えると、シェルは command
に渡す 0 番目のオプションの先頭にダッシュを設定します。 こ れ は
login(1) が行う動作です。 -c オプションを与えると、 command は空
の環境で実行されます。 -a を与えると、シェルは実行するコマンドに
0 番目の引き数として name を渡します。何らかの理由で command が
実行できない場合には非対話的シェルは終了します。ただしシェルオプ
ション execfail が設定されている場合は終了せず、この場合には偽が
返されます。ファイルが実行できない場合には、対話的シェルは偽を返
し ます。 command が指定されていない場合、任意のリダイレクトはカ
レントシェルで効果を表し、終了ステータスは 0 となります。リダ イ
レクトのエラーが起きた場合には、終了ステータスは 1 となります。
exit [n]
ステータス n でシェルを終了させます。 n を省略すると、終了ステー
タスは最後に実行したコマンドの終了ステータスとなります。シェルが
終了する前には、 EXIT に対するトラップが実行されます。
export [-fn] [name[=word]] ...
export -p
与えられた name には印が付けられ、これ以降に実行するコマンドの環
境に自動的にエクスポートされるようになります。 -f オプションを与
え る と、 name は関数を参照します。 name を与えなかった場合や、
-p オプションを与えた場合には、このシェル内でエクスポートされ て
いる全ての名前のリストが出力されます。 -n オプションを与えると、
指定した変数からエクスポート属性が取り除かれます。不正なオプショ
ンがあった場合、 name のいずれかが不正なシェル変数名であった場合
、関数でない名前に対して -f オプションを与えた 場 合 を 除 き 、
export は終了ステータス 0 を返します。
fc [-e ename] [-nlr] [first] [last]
fc -s [pat=rep] [cmd]
フ ィ ッ クスコマンド (Fix Command)。最初の形式では、 first から
last までの範囲のコマンドが履歴リストから選択されます。 first と
last は文字列 (その文字列で始まる最後のコマンド) や数値 (履歴リ
スト中でのインデックス。負の値は現在のコマンド番号からのオフセッ
トとして扱われます) としても指定できます。 last が指定されていな
ければ、リスト表示の場合には現在のコマンドが設定され (したがって
‘‘fc -l -10’’ で最近のコマンド 10 個が出力されます)、それ以外の
場合には first が設定されます。 first が指定されていなければ、編
集 の場合には前のコマンドが設定され、リスト表示の場合には -16 が
設定されます。
-n オプションを与えるとリストにコマンド番号が付きません。 -r オ
プションを与えるとコマンドの順序が逆になります。 -l オプションを
与えると、コマンドは標準出力にリスト表示されます。それ以外の場合
に は、これらのコマンドが書かれたファイルに対し、 ename で指定し
たエディタが起動されます。 ename が与えられていない場合は、変 数
FCEDIT の値が使われ、 FCEDIT も設定されていない場合には EDITOR
の値が使われます。どちらの変数も設定されていなければ、 vi が使わ
れます。編集が終了すると、編集されたコマンドがエコー表示され、実
行されます。
2 番目の形式では、pat の部分をそれぞれ rep で置き換えた後に com-
mand が 再 実 行されます。これを利用している便利なエイリアスに
‘‘r=fc -s’’ があります。これを用いると ‘‘r cc’’ と入 力 す れ ば
‘‘cc’’ で始まる最も新しいコマンドを実行でき、 ‘‘r’’ の入力すれば
直前のコマンドを再実行できます。
最初の形式を用いた場合、不正なオプションがあるか、 first また は
last が履歴行の範囲外を指定していなければ、返り値は 0 となります
。 -e オプションが与えられた場合、返り値は最後に実行されたコマン
ドの返り値となるか、あるいはコマンドの一時ファイルでエラーが起き
た場合には偽となります。 2 番目の形式を用いた場合、終了ステー タ
スは再実行されたコマンドの終了ステータスとなります。ただし、 cmd
が有効な履歴行を指定していない場合は別で、この場合には fc は偽を
返します。
fg [jobspec]
jobspec の実行をフォアグラウンドで再開し、これをカレントジョブと
します。 jobspec が無い場合、シェルが記録しているカレントジョ ブ
が使われます。返り値はフォアグラウンドで再開されたコマンドの返り
値ですが、ジョブ制御が無効であるときに実行した場合や、ジョブ制御
が 有 効 であっても jobspec が有効なジョブを指定していない場合や
jobspec がジョブ制御無しで実行したジョブを指定している場合には偽
となります。
getopts optstring name [args]
getopts はシェルの手続きが位置パラメータを解釈するために使います
。 optstring は識別の対象であるオプション文字列です。ある文字 の
後にコロンがある場合、そのオプションは引き数を取ることが期待され
ます。引き数は空白でオプション文字と区切られていなければなりませ
ん。コロンと疑問符はオプション文字として使えません。呼び出される
度に、 getopts は次に見つかったオプションをシェル変数 name に 格
納し (name が存在しなければ初期化を行います)、次に処理される引き
数のインデックスを変数 OPTIND に格納します。 OPTIND はシェルまた
は シェルスクリプトが呼び出される度に 1 に初期化されます。オプシ
ョンが引き数を必要とする場合には、 getopts はその引き数 を 変 数
OPTARG に格納します。シェルが OPTIND を自動的に再設定することは
ありません。 1 つのシェルが呼び出されている間に別のパラメータ の
組 合せを使う場合には、 getopts の呼び出しの間に手動で再設定を行
わなければなりません。
オプションの終わりに到達すると、 getopts は 0 より大きい返り値で
終了します。 OPTIND にはオプションでない最初の引き数のインデック
スが設定され、 name には ? が設定されます。
getopts は通常位置パラメータを展開しますが、他の引き数が args に
指 定されている場合には、 getopts は位置パラメータでなくこれらを
展開します。
getopts は 2 通りの方法でエラーを報告できます。 optstring の最初
の 文字がコロンならば、 静かな (silent) エラー報告が行われます。
通常の操作では、不正なオプションがある場合やオプションの引き数が
足 りない場合に診断メッセージが出力されます。変数 OPTERR に 0 が
設定されている場合、エラーメッセージは全く出力されません。これは
、 optstring の最初の文字がコロンでなくても同じです。
不正なオプションがあった場合、 getopts は ? を name に設定します
。さらに、静かなモードでない場合にはエラーメッセージが出力され、
OPTARG の設定が取り消されます。 getopts が静かなモードであれば、
見つかったオプション文字は OPTARG に設定され、診断メッセージは出
力されません。
必 要な引き数が見つからず、かつ getopts が静かなモードでない場合
には、疑問符 (?) が name に設定され、 OPTARG の設定が取り消さ れ
、 診断メッセージが出力されます。 getopts が静かなモードならば、
コロン (:) が name に設定され、 OPTARG には見つかったオプショ ン
文字が設定されます。
(指定の有無に関係なく) オプションが見つかった場合、 getopts は真
を返します。オプションの最後に到達した場合や、エラーが起きた場合
には、 getopts は偽を返します。
hash [-r] [-p filename] [name]
name それぞれに対して、 $PATH 内のディレクトリの検索を行ってコマ
ンドの完全なファイル名を調べ、その結果を記憶します。 -p オプショ
ンが指定されると、パス検索は実行されず、 filename がそのコマンド
の完全なファイル名として使われます。 -r オプションを与えると、シ
ェルは記憶している位置を全て忘れます。引き数が与えられていない場
合は、記憶しているコマンドに関する情報が出力されます。 name が見
つからない場合と不正なオプションが与えられた場合を除き、返却ステ
ータスは真となります。
help [-s] [pattern]
組み込みコマンドのヘルプ情報を表示します。 pattern が指定され た
場 合には、 help はこの pattern にマッチする全てのコマンドに関す
る詳しいヘルプを出力します。それ以外の場合には、全ての組み込みコ
マンドと制御構造についての説明が出力されます。 -s オプションは、
表示されるヘルプ情報を短い書式の使用法に限定します。 pattern に
マ ッチするコマンドが全くない場合を除き、返却ステータスは 0 です
。
history [n]
history -c
history -d offset
history -anrw [filename]
history -p arg [arg ...]
history -s arg [arg ...]
オプションがない場合には、行番号付きでコマンド履歴を表示します。
* 付きでリスト表示されている行は変更された行です。引き数 n を指
定すると、最新の n 行だけがリスト表示されます。 filename が与 え
られている場合、これは履歴ファイルの名前として使われます。これが
与えられていない場合には HISTFILE の値が使われます。(指定され て
いれば) オプションは以下の意味を持ちます:
-c 履歴リストの全てのエントリを削除し、クリアします。
-d offset
offset 番目にある履歴エントリを削除します。
-a 「新しい」履歴行 (bash の現在のセッションの開始以来入力さ
れた履歴行) を履歴ファイルに追加します。
-n まだ履歴ファイルから読み込んでいない履歴行を現在の履歴 リ
ストに読み込みます。これらは、bash の現在のセッションの開
始以降に履歴ファイルに追加された行です。
-r 履歴ファイルの内容を読み込み、これらを現在の履歴として 用
います。
-w 現在の履歴を履歴ファイルに書き込みます。履歴ファイルの内
容は上書きされます。
-p 後に続く args に対して履歴置換を行い、その結果を標準出 力
に 表示します。この結果は履歴リストには格納されません。通
常の履歴展開が行われないようにするため、 arg はそれぞれク
ォートしなければなりません。
-s args を 1 つのエントリとして履歴リストに格納します。履歴
リストの最後のコマンドは、 args が追加される前に削除さ れ
ます。
不正なオプションがある場合、履歴ファイルの読み書きの間にエラーが
起きた場合、 -d オプションの引き数として不正な offset の値が与え
られた場合、 -p オプションの引き数として与えられた履歴展開が失敗
した場合を除き、返り値は 0 になります。
jobs [-lnprs] [ jobspec ... ]
jobs -x command [ args ... ]
最初の形式を実行すると、アクティブなジョブがリスト表示されます。
オプションは以下の意味を持ちます:
-l 通常の情報に加えて、プロセス ID をリスト表示します。
-p そのジョブが属するプロセスグループのリーダーのプロセス ID
だけを表示します。
-n ユーザがステータスを最後に通知されて以来、ステータスの 変
更があったジョブに関する情報だけを表示します。
-r 実行中のジョブだけを出力します。
-s 停止中のジョブだけを出力します。
jobspec が与えられている場合、そのジョブに関する情報だけが出力さ
れるます。不正なオプションがある場合や、不正な jobspec が与え ら
れた場合を除き、返却ステータスは 0 です。
-x オプションが与えられた場合、 jobs は command や args 中で見つ
かった jobspec を全て対応するプロセスグループ ID に置き 換 え 、
args を渡して command を実行し、その終了ステータスを返します。
kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ...
kill -l [sigspec | exit_status]
sigspec または signum で指定されたシグナルを、 pid または job-
spec で指定されたプロセスに送ります。 sigspec は SIGKILL のよ う
なシグナル名、またはシグナルの番号です。 signum はシグナルの番号
です。 sigspec がシグナル名ならば、その名前には SIG プレフィック
ス は あ っ て も 無 くても構いません。 sigspec が無い場合には、
SIGTERM が指定されたものとします。引き数に -l を与えるとシグナル
名がリスト表示されます。 -l と同時に引き数を与えると、引き数に対
応するシグナルの名前がリスト表示され、返却ステータスは 0 とな り
ま す。 -l に対する引き数 exit_status は、シグナル番号、またはシ
グナルによって終了させられたプロセスの終了ステータスを指定する数
で す。少なくとも 1 つのシグナルを正常に送れた場合、 kill は真を
返します。エラーが起きた場合や不正なオプションがあった場合には、
kill は偽を返します。
let arg [arg ...]
各 arg は評価される算術式です ( 算術式展開を参照)。最後の arg を
評価した結果が 0 であれば、 let は 1 を返します。それ以外の場 合
には 0 が返されます。
local [option] [name[=value] ...]
それぞれの引き数に対して name という名前のローカル変数が生成され
、 value が代入されます。 option には、 declare コマンドに使える
オ プションがすべて使えます。関数内で local を使った場合、この変
数 name の可視スコープは、この関数とこの関数の子に制限されます。
オ ペランドが無い場合、 local はローカル変数の一覧を標準出力に出
力します。関数の内部以外で local を使うとエラーに な り ま す 。
local が 関 数の外部で使われたり、不正な name が与えられたり、
name が読み取り専用であったりしなければ、 local の返却ステータス
は 0 となります。
logout ログインシェルを終了します。
popd [-n] [+n] [-n]
ディレクトリスタックからエントリを削除します。引き数が無い場合に
は、スタック先頭のディレクトリが削除され、新しく先頭となったディ
レクトリへの cd が実行されます。引き数が指定された場合には、これ
は以下の意味を持ちます:
+n dirs で表示されるリストの左から数えて n 番目のエントリ を
削 除 し ます。エントリは 0 から数えます。例えば、 ‘‘popd
+0’’ は最初のディレクトリを削除し、 ‘‘popd +1’’ は 2 番目
のディレクトリを削除します。
-n dirs で表示されるリストの右から数えて n 番目のエントリを
削除します。エントリは 0 から数えます。例え ば 、 ‘‘popd
-0’’ は最後のディレクトリを削除し、 ‘‘popd -1’’ は最後の
1 つ前のディレクトリを削除します。
-n スタックからディレクトリを削除する際に、通常のディレク ト
リ 変更を行いません。したがって、スタックだけが操作されま
す。
popd コマンドが成功すれば、 dirs も実行され、返却ステータスは 0
となります。 popd が偽を返すのは、不正なオプションがあった場合・
ディレクトリスタックが空の場合・ディレクトリスタックの存在しない
エントリが指定された場合・ディレクトリ変更に失敗した場合です。
printf format [arguments]
arguments を整形して標準出力に書き出します。フォーマットは for-
mat で制御します。 format は 3 つのタイプのオブジェクトを含む 文
字列です。 3 つのオブジェクトとは、(そのまま標準出力にコピーされ
る) プレーン文字・ (変換されて標準出力にコピーされる) 文字エスケ
ープシーケンス・ (その後に続く引き数 argument それぞれの表示に用
いられる) 表示フォーマット指定、です。 printf(1) 標準のフォー マ
ット以外に、以下のフォーマットが使えます。 %b を用いると、printf
は対応する argument 中のバックスラッシュのエスケープシーケンスを
展 開します。また %q を用いると、printf は対応する argument をシ
ェルの入力として再利用できるフォーマットで出力します。
format は必要に応じて再利用され、全ての arguments を処理します。
与 えられたよりも多くの arguments を format が必要とする場合、余
分のフォーマット指定は、 0 と空文字列のうち、適切な方が指定さ れ
た かのように動作します。成功した場合の返り値は 0 で、失敗した場
合の返り値は 0 以外です。
pushd [-n] [dir]
pushd [-n] [+n] [-n]
ディレクトリをディレクトリのスタックに追加するか、スタックをロー
テートさせます。この時、新しいスタックの最も上にあるものをカレン
トの作業ディレクトリにします。引き数を与えなければ、一番上 の 2
つのディレクトリを交換し、0 を返します。ただし、ディレクトリスタ
ックが空の場合を除きます。引き数を与えた場合には、以下の意味を持
ちます:
+n スタックをローテートさせ、n 番目のディレクトリを一番上に
します。このとき dirs が表示するリストは左から数え始め 、
その左端は 0 となります。
-n スタックをローテートさせ、n 番目のディレクトリを一番上に
します。このとき dirs が表示するリストは右から数え始め 、
その右端は 0 となります。
-n ディレクトリをスタックに追加した時に、通常のディレクトリ
変更を行いません。したがって、スタックだけが操作されま す
。
dir dir をディレクトリスタックの一番上に追加します。また、こ
のディレクトリを新しいカレントの作業ディレクトリにしま す
。
pushd コマンドが成功すると、 dirs コマンドも実行されます。最初の
形式を使った場合、 dir への cd が失敗しなければ、 pushd は 0 を
返 し ます。 2 番目の形式を使った場合にも、 pushd は基本的には 0
を返します。ただし、ディレクトリスタックが空の場合・ディレクトリ
スタックの存在しない要素が指定された場合・指定された新しいカレン
トディレクトリへのディレクトリ変更が失敗した場合は除きます。
pwd [-LP]
現在の作業ディレクトリの絶対パス名を出力します。 -P オプションが
指定された場合や、組み込みコマンド set の -o physical オプション
が有効になっている場合には、出力されるパス名にはシンボリックリン
クは含まれません。 -L オプションを使うと、出力されるパス名にはシ
ンボリックリンクが含まれているかもしれません。カレントディレクト
リの名前を読む際にエラーが起きたり、不正なオプションが与えられな
ければ、返却ステータスは 0 となります。
read [-ers] [-t timeout] [-a aname] [-p prompt] [-n nchars] [-d delim]
[name ...]
標準入力から 1 行を読み込み、最初の単語を最初の name に代入し、2
番 目の単語を 2 番目の name に代入します。以降も同様です。余った
単語とそれらの間の区切り文字は、最後の name に代入さ れ ま す 。
name よりも標準入力から読み込んだ単語の方が少ない場合には、余っ
ている name には空文字列が値として代入されます。 IFS 中の文字 が
、 行 を単語に分割するために使われます。バックスラッシュ文字 (\)
を使うと、次に読み込んだ文字の特殊な意味を消したり、行を連結した
りできます。オプションが与えられていれば、以下の意味を持ちます:
-a aname
単語を配列変数 aname にインデックス順に代入します。インデ
ックスは 0 から始まります。新しい値が代入される前に は 、
aname の設定は消されます。他の name 引き数は無視されます
。
-d delim
改行ではなく、delim の最初の文字が、入力行を終了するた め
に使われます。
-e 標 準入力を端末から読み込む場合、 readline (前述の READ-
LINE ライブラリのセクションを参照) を使って行を取得します
。
-n nchars
組 み込みコマンド read は、入力行全体が読み込まれるのを待
たず、文字 nchars を読み込んだ時に戻ります。
-p prompt
入力を読み込もうとする前にプロンプトを表示します。末尾 に
改 行は付きません。プロンプトが表示されるのは、入力を端末
から読み込む場合だけです。
-r バックスラッシュはエスケープ文字として作用しません。バ ッ
ク スラッシュは行の一部と見なされます。特に、バックスラッ
シュと改行の組合せを使って複数の行を接続することはでき ま
せん。
-s 静かな (silent) モード。端末に入力が行われても、文字はエ
コーされません。
-t timeout
入力行全体が timeout 秒以内で読み込まれない場合、 read を
タ イムアウトさせて、失敗の状態を返します。このオプション
は、 read が入力を端末やパイプから読み込んでいない場合 、
何も効果がありません。
name が全く与えられていない場合、読み込まれた行は変数 REPLY に代
入されます。ファイル末尾に到達したり read がタイムアウトしたりし
なければ、終了コードは 0 です。
readonly [-apf] [name ...]
指定された name に読み込み専用の印を付けます。それ以降は、このよ
うな name の値を変更することはできません。 -f オプションを与えた
場 合、name に対応する関数に同様の印が付きます。 -a オプション与
えると、配列変数だけが対象となります。 name 引き数が全く与えられ
てない場合、または -p オプションが与えられた場合、読み込み専用の
名前全ての一覧が出力されます。 -p オプションを使うと、入力として
再利用できるようなフォーマットで出力が行われます。返却ステータス
は基本的に 0 ですが、不正なオプションがあった場合、 name のい ず
れかが有効なシェル変数名で無かった場合、 -f オプションに関数でな
い name を与えた場合は除きます。
return [n]
指定した返り値 n で関数を終了させます。 n を省略すると、返却ステ
ータスは関数内で最後に実行したコマンドの返却ステータスになります
。関数の外側で使われているが、 . (source) コマンドによるスク リ
プ ト の実行中である場合、シェルはそのスクリプトの実行を止め、 n
またはスクリプト内で最後に実行されたコマンドの終了ステータスをス
ク リプトの終了ステータスとして返します。関数の外側で . によるス
クリプトの実行中以外に使われた場合、返却ステータスは偽となります
。
set [--abefhkmnptuvxBCHP] [-o option] [arg ...]
オプション無しの場合は、シェル変数全ての名前と値の組が表示されま
す。表示は、入力として再利用できるフォーマットで行われます。出力
は現在のロケールに従ってソートされます。オプションが指定されてい
る場合、オプションはシェルの属性を設定または解除します。オプショ
ンが処理された後に残っている引き数があれば、これは位置パラメータ
の値として扱われ、 $1, $2, ... $n の順に代入されます。オプシ ョ
ンが指定されていれば、以下の意味を持ちます:
-a 値を変更したり新規に設定したりした変数および関数が、自動
的に (後に実行するコマンドの) 環境としてエクスポートされ
るようになります。
-b 終了したバックグラウンドジョブのステータス報告を、次のプ
ライマリプロンプトの前ではなく、即座に行います。これはジ
ョブ制御が有効な場合に限り有効です。
-e 単純なコマンド (前述の シェルの文法セクションを参照) が
0 でないステータスで終了した場合、即座に終了します。ただ
し失敗したコマンドが until または while ループの一部であ
る、 if 文の一部である、 && または ││ リストの一部である
、コマンドの返り値が ! で反転されている、のいずれかの場
合にはシェルは終了しません。
-f パス名展開を無効にします。
-h コマンドの位置を記憶し、実行時にこれを引きます。これはデ
フォルトで有効になっています。
-k 代入文の形式を持つ全ての引き数を、コマンドに対する環境に
追加します。環境変数となるのは、コマンド名の前にあるもの
に限りません。
-m 監視モード。ジョブ制御は有効になります。ジョブ制御 (前述
の ジョブ制御セクションを参照) をサポートしているシス テ
ム上の対話的シェルでは、このオプションはデフォルトで有効
です。別のプロセスグループで実行されたバックグラウンドプ
ロセスと、これらの終了ステータスが書かれた行が、プロセス
の終了時に表示されます。
-n コマンドを読み込みますが実行はしません。これを使うとシェ
ルスクリプトの文法エラーをチェックできます。このオプショ
ンは対話的シェルでは無視されます。
-o option-name
option-name には、以下のいずれかを指定できます:
allexport
-a と同じです。
braceexpand
-B と同じです。
emacs emacs 形式のコマンド行編集インタフェースを使いま
す。これはシェルが対話的な場合には、デフォルトで
有効です。ただし、 --noediting オプション付き で
シェルを実行した場合は除きます。
errexit -e と同じです。
hashall -h と同じです。
histexpand
-H と同じです。
history コマンド履歴を有効にします。コマンド履歴について
は 履歴セクションで説明しています。このオプシ ョ
ンは、対話的シェルではデフォルトで有効です。
ignoreeof
効果は、シェルコマンドの ‘‘IGNOREEOF=10’’ を実行
した場合と同様です (前述の シェル変数を参照)。
keyword -k と同じです。
monitor -m と同じです。
noclobber
-C と同じです。
noexec -n と同じです。
noglob -f と同じです。
notify -b と同じです。
nounset -u と同じです。
onecmd -t と同じです。
physical
-P と同じです。
posix bash の動作を変えます。デフォルトの操作は POSIX
1003.2 標準と異なりますが、これを標準に準拠する
ようにします (posix モード)。
privileged
-p と同じです。
verbose -v と同じです。
vi vi 形式のコマンド行編集インタフェースを使いま す
。
xtrace -x と同じです。
option-name 無しで -o オプションを与えた場合、現在のオプ
ションが出力されます。 option-name 無しで +o オプショ ン
を 与えた場合、現在のオプション設定を再生成する set コマ
ンドの列が標準出力に出力されます。
-p 特権 (privileged) モードを有効にします。このモード で は
$ENV と $BASH_ENV ファイルは処理されず、シェル関数は環境
から継承されず、 SHELLOPTS 環境変数は定義されていても 無
視されます。シェルを起動した時に実効ユーザ (グループ) ID
が実ユーザ (グループ) ID と異なり、かつ -p オプション が
与 え られていない場合、これらの動作が行われ、実効ユーザ
ID には実ユーザ ID が設定されます。起動時に -p オプシ ョ
ンが与えられた場合、実効ユーザ ID は再設定されません。こ
のオプションを無効にすると、実効ユーザ ID と実効グループ
ID には実ユーザ ID と 実グループ ID が設定されます。
-t コマンドを 1 つ読み込み、実行してから終了します。
-u パラメータ展開の実行中に、設定が取り消されている変数をエ
ラーとして扱います。設定が取り消されている変数を展開しよ
うとした場合、シェルはエラーメッセージを出力します。シェ
ルが対話的でなければ、0 でないステータスで終了します。
-v シェルの入力行を、読み込んだ際に表示します。
-x 単純なコマンドをそれぞれ展開した後、 PS4 を展開した値 を
表示し、その後にそのコマンドと展開した引き数を表示します
。
-B シェルはブレース展開 (前述の ブレース展開を参照) を実 行
します。これはデフォルトで有効です。
-C 設定されている場合、 bash はリダイレクト演算子 >, >&, <>
で既存のファイルを上書きしません。上書きができるのは、リ
ダイレクト演算子 >| を > の代わりに使った時です。
-H ! 形式の履歴置換を有効にします。このオプションは、シェ
ルが対話的な時にはデフォルトで有効です。
-P 設定されている場合、 cd のような現在の作業ディレクトリを
変更するコマンドを実行する時に、シェルはシンボリックリン
クを辿りません。代わりに物理的ディレクトリ構造が使われま
す。デフォルトでは、 bash がカレントディレクトリを変更す
るコマンドを実行する際には、ディレクトリの論理的な接続が
辿られます。
-- このオプションの後に引き数が続いていない場合には、位置パ
ラメータの設定が取り消されます。それ以外の場合には、位置
パラメータに arg の残りが設定されます。これらに - で始ま
るものが含まれていても、オプションではなく位置パラメータ
として扱われます。
- オ プションの終わりを示します。残りの arg は全て位置パラ
メータに代入されます。 -x オプションと -v オプションは無
効 になります。 arg が無い場合には、位置パラメータの内容
は変化しません。
特に断らない限り、各オプションはデフォルトで無効になっています。
- の代わりに + を使うと、これらのオプションは無効になります。オ
プションはシェルを起動する際の引き数としても指定できます。現在の
オプションの集合は、 $- で知ることができます。不正なオプションが
無ければ、終了ステータスは必ず真となります。
shift [n]
n+1 ... からの位置パラメータの名前を変え、 $1 ... とします。 $#
か ら $#-n+1 までの数字で表されるパラメータは unset されます。 n
は 0 以上 $# 以下の数でなければなりません。 n が 0 ならば、ど の
パ ラメータも変更されません。 n が与えられない場合には、1 が指定
されたものと見なされます。 n が $# より大きい場合、位置パラメ ー
タは変化しません。 n が $# より大きい場合や 0 より小さい場合には
、返却ステータスは 0 より大きい数になります。それ以外の場合に は
0 になります。
shopt [-pqsu] [-o] [optname ...]
シェルのオプション動作を制御する変数の値をトグルさせます。オプシ
ョンが無い場合や、 -p オプションが指定されている場合には、設定可
能なオプション全てのリストが表示されます。表示の際には、それぞれ
が設定されているかどうかも示されます。 -p オプションが指定されて
いると、オプションの表示は、入力として再利用できるフォーマットで
行われます。その他のオプションは、以下の意味を持っています:
-s optname をそれぞれ有効にします (設定します)。
-u optname をそれぞれ無効にします (設定解除します)。
-q 通常の出力を止めます (静かなモード)。返却ステ ー タ ス は
optname が設定されているかどうかを示します。複数の opt-
name 引き数と -q が指定されている場合には、全 て の opt-
names が有効である時に返却ステータスが 0 となります。それ
以外の時には、0 でない値となります。
-o optname の値を、組み込みコマンド set の -o オプションで定
義されているものに制限します。
引 き数 optname 無しで -s オプションまたは -u オプションを使った
場合、表示されるものは設定されているもの、または設定されていない
ものにそれぞれ制限されます。特に断らない限り、shopt オプションは
デフォルトで無効 (設定解除) になっています。
オプションをリスト表示した時の返却ステータスは、全ての optnames
が有効になっている場合は 0 となります。それ以外の場合には 0 でな
い値となります。設定または設定取り消しのオプションの 時 に は 、
optname が不正なシェルオプションでなければ、返却ステータスは 0
となります。
shopt オプションのリストを以下に示します:
cdable_vars
設定されている場合、組み込みコマンド cd への引き数でディ
レクトリでないものは変数の名前と見なされ、その値が変更先
のディレクトリとなります。
cdspell 設定されている場合、 cd コマンドのディレクトリ要素におけ
るスペルのちょっとした誤りは修正されます。チェックされる
誤りは、文字の入れ替わり・文字の欠け・ 1 文字余分にあ る
ことです。訂正できた場合には、訂正後のファイル名が表示さ
れ、コマンドは続けて実行されます。このオプションが使われ
るのは対話的シェルだけです。
checkhash
設定されている場合、 bash はハッシュ表で見つけたコマンド
を実行する前に実際に存在するかどうかをチェックします。ハ
ッシュされているコマンドが既に無くなっている場合、通常の
パス検索が行われます。
checkwinsize
設定されている場合、bash はコマンドの実行後に毎回ウィ ン
ド ウの大きさをチェックし、必要に応じて LINES と COLUMNS
の値を更新します。
cmdhist 設定されている場合、 bash は複数行に分かれているコマンド
の全ての行を、同じ履歴エントリに保存しようとします。これ
を使うと、複数行に分かれているコマンドの再編集が容易にな
ります。
dotglob 設定されている場合、 bash は ‘.’ で始まるファイル名をパ
ス名展開の結果に含めます。
execfail
設定されている場合、組み込みコマンド exec への引き数とし
て指定されたファイルが実行できなくても、対話的でないシェ
ルが終了しません。対話的シェルは exec に失敗しても終了し
ません。
expand_aliases
設 定されている場合、エイリアスが前述の エイリアスセクシ
ョンで説明したように展開されます。このオプションは、対話
的なシェルではデフォルトで有効です。
extglob 設定されている場合、拡張されたパターンマッチング機能が有
効になります。これについては、前述のパス名展開で説明して
います。
histappend
設 定 さ れ ている場合、シェルの終了時に履歴リストが変数
HISTFILE の値で指定しているファイルに追加されます。フ ァ
イルへの上書きは行われなくなります。
histreedit
この変数が設定されており、かつ readline が使われている場
合、ユーザは失敗した履歴置換を再編集できます。
histverify
この変数が設定されており、かつ readline が使われている場
合、履歴置換の結果は即座にはシェルのパーザに渡されません
。その代わり、結果として得られた行は readline の編集バッ
ファに読み込まれ、さらに修正できます。
hostcomplete
この変数が設定されており、かつ readline が使われている場
合、bash は @ を含む単語を補完する時にホスト名補完を実行
しようとします (前述の READLINE ライブラリのセクションに
おける 補完を参照)。これはデフォルトで有効になっています
。
huponexit
設 定されている場合、bash は対話的なログインシェルを終了
する時に、全てのジョブに SIGHUP を送ります。
interactive_comments
設定されている場合、 # で始まる単語について、その単語 と
その行の残りの文字を対話的シェルに無視させることができま
す (前述の コメントセクションを参照)。このオプションはデ
フォルトで有効になっています。
lithist 設定されており、かつ cmdhist オプションが有効ならば、複
数行に分かれているコマンドは (セミコロンで区切られるので
はなく) できる限り途中に改行を埋め込むことで履歴に保存さ
れます。
mailwarn
設定されており、かつ bash がメールをチェックするファイル
が前回のチェック以降にアクセスされている場合、メッセージ
‘‘The mail in mailfile has been read’’ が表示されます。
no_empty_cmd_completion
設定されており、かつ readline が使われている場合、空行に
対してコマンド補完をさせようとしたときに、 bash は補完用
の PATH 検索を行いません。
nocaseglob
設定されている場合、 bash はパス名展開 (前述の パス名 展
開を参照) を行う時に、ファイル名の大文字と小文字を区別せ
ずにマッチングを行います。
nullglob
設定されている場合、 bash はどのファイルにもマッチしない
パ ターン (前述の パス名展開を参照) を、その文字列自身で
はなく、空文字列に展開します。
progcomp
設定されている場合、プログラム補完機能 (前述のプログラム
補完を参照) が有効になります。このオプションはデフォルト
で有効になっています。
promptvars
設定されている場合、プロンプト文字列に対して変数展開とパ
ラ メータ展開が行われます。この展開は前述の プロンプトセ
クションで説明した展開が行われた後に行われます。このオプ
ションはデフォルトで有効になっています。
restricted_shell
シェルが制限モードで起動された場合、このオプションが設定
されます (後述の 制限付きのシェルセクションを参照)。この
値を変更することはできません。これは起動ファイルが実行さ
れる時にもリセットされないので、シェルが制限付きかどうか
を起動ファイル内部で知ることができます。
shift_verbose
設 定されている場合、組み込みコマンド shift においてシフ
トの回数が位置パラメータの数を超えると、エラーメッセージ
が出力されます。
sourcepath
設 定されている場合、組み込みコマンド source (.) は PATH
の値を使って、引き数として与えられたファイルを含むディレ
クトリを見つけます。このオプションはデフォルトで有効です
。
xpg_echo
設定されている場合、組み込みコマンド echo はデフォルトで
バックスラッシュによるエスケープシーケンスを展開します。
suspend [-f]
SIGCONT シグナルを受け取るまで、シェルの実行をサスペンドします。
suspend は、ログインシェルをサスペンドできません。しかし、 -f オ
プションを与えた場合、シェルがログインシェルであってもサスペンド
できます。シェルがログインシェルかつ -f が与えられていない場合、
またはジョブ制御が有効でない場合を除いて、返却ステータスは 0 で
す。
test expr
[ expr ]
条件式 expr を評価した結果に基づいて、ステータス 0 または 1 を返
します。演算子とオペランドそれぞれは別々の引き数でなければなりま
せ ん。式は前述の 条件式セクションで説明したプライマリで構成され
ます。
式は次に示す演算子を使って結合できます。優先度の高い順に示します
。
! expr expr が偽ならば真になります。
( expr )
expr の値を返します。これを使うと、通常の演算子の優先度を
変更できます。
expr1 -a expr2
expr1 と expr2 が両方とも真ならば真になります。
expr1 -o expr2
expr1 と expr2 のいずれかが真ならば真になります。
test および [ は、引き数の数に基づいた規則の集合を用いて条件式を
評価します。
引き数が 0 個
この式は偽です。
引き数が 1 個
引き数が空でない場合に限り真になります。
引き数が 2 個
最 初の引き数が ! ならば、 2 番目の引き数が空の場合に限り
真になります。最初の引き数が、既に 条件式セクションで説明
し た単項条件演算子のいずれかであれば、単項の評価が真の場
合に式は真となります。最初の引き数が正しい単項条件演算 子
でなければ、式は偽となります。
引き数が 3 個
2 番目の引き数が、既に 条件式セクションで説明した二値条件
演算子のいずれかであれば、最初と 3 番目の引き数をオペラン
ド として使った二値評価の結果が式の結果となります。最初の
引き数が ! であれば、2 番目と 3 番目の引き数を使った、 引
き数 2 つの評価の結果を否定したものが値となります。最初の
引き数が ( であり、3 番目の引き数が ) ならば、 2 番目の引
き数を使って引き数 1 つの評価を行った値が結果となります。
これら以外の場合には、式は偽となります。この場合におい て
は、-a と -o は二値演算子として扱われます。
引き数が 4 個
最 初の引き数が ! ならば、残りの引き数で作った引き数 3 つ
の式の値を否定したものが結果となります。それ以外の場合 に
は 、先に挙げた規則を使った優先度に従って式が展開・評価さ
れます。
引き数が 5 個以上
先に挙げた規則を使った優先度に従って式が展開・評価され ま
す。
times シェルとシェルから実行したプロセスについて、ユーザ時間とシステム
時間を加えたものを出力します。返却ステータスは 0 です。
trap [-lp] [arg] [sigspec ...]
シェルがシグナル sigspec を受け取ると、コマンド arg が読み込まれ
て、実行されます。 arg が存在しないか、 - である場合、指定されて
いるシグナルは全て最初の値 (シェルの起動時に設定されていた値) に
リ セットされます。 arg が空文字列である場合、それぞれの sigspec
で指定されているシグナルは、シェルとシェルが起動したコマンドから
無 視 さ れ ま す。 arg なしで -p オプションが与えられた場合、各
sigspec に対応する trap コマンドが表示されます。引き数が全く無い
か、 -p だけが与えられた場合、 trap は各シグナル番号に対応するコ
マンドのリストを出力します。それぞれの sigspec は、 で
定義されているシグナル名またはシグナル番号です。 sigspec が EXIT
(0) であれば、シェルの終了時にコマンド arg が実行 さ れ ま す 。
sigspec が DEBUG であれば、単純なコマンド (前述の シェルの文法セ
クションを参照) が終わるたびにコマンド arg が実行されます 。 -l
オプションを与えると、シェルはシグナル名とこれに対応する番号のリ
ストを出力します。シェルのエントリで無視されるシグナルは、トラッ
プもリセットもできません。トラップされたシグナルはリセットされ、
子プロセスが生成された時の最初の値に戻ります。 sigspec のいず れ
かが不正であれば、返却ステータスは偽になります。それ以外の場合に
は、 trap は真を返します。
type [-atp] name [name ...]
オプション無しの場合には、各 name をコマンド名として使ったときに
、それがどのように解釈されるかを示します。 -t オプションを使うと
、 name が、エイリアス・シェルの予約語・関数・組み込みコマンド・
デ ィ スク上のファイルのいずれかの場合、 type はそれぞれに応じて
alias, keyword, function, builtin, file という文字列を出力します
。 name が見つからない場合は何も出力されず、偽の終了ステータスが
返されます。 -p オプションを使うと、 type は name をコマンド名と
して指定した場合に実行されるディスクファイルの名前、または空文字
列を返します。空文字列が返されるのは、 ‘‘type -t name’’ が file
を返さない場合です。コマンドがハッシュされている場合、 -p はハッ
シュされている値を表示します。表示されるのは、必ずしも PATH 中で
最 初 に現われるファイルとは限りません。 -a オプションを使うと、
type は name が示す実行ファイルがある場所を全て出力します 。 -p
オプションが同時に使われていない場合に限り、エイリアスや関数も出
力されます。 -a を使う時には、ハッシュされているコマンドの表は参
照されません。 type は、引き数のいずれかが見つかれば真を返し、ど
れも見つからなければ偽を返します。
ulimit [-SHacdflmnpstuv [limit]]
これを使うと、シェルおよびシェルが起動するプロセスが利用できるリ
ソースを制御できます。ただし、このような制御ができるシステムの場
合に限ります。 limit の値はリソースに対して指定されている単位 の
数 、または unlimited です。 -H オプションと -S オプションは、そ
れぞれ与えられたリソースに対する強い (hard) 制限と弱い (soft) 制
限を設定します。強い制限は一度設定すると増やせません。弱い制限は
強い制限の値までは増やせます。 -H と -S がどちらも指定されていな
い 場合、強い制限と弱い制限がどちらも設定されます。 limit を省略
すると、リソースの弱い制限の現在値が表示されます。ただし、-H が
与えられている場合は除きます。複数のリソースが指定されている時は
、制限名と単位が値の前に出力されます。他のオプションは以下のよう
に解釈されます:
-a 現在の制限を全て報告する
-c 生成されるコアファイル (core) の最大サイズ
-d プロセスのデータセグメントの最大サイズ
-f シェルが生成できるファイルの最大サイズ
-l メモリにロックできる最大サイズ
-m 常駐セットサイズの最大値
-n オープンできるファイル・ディスクリプターの最大数 (ほとん
どのシステムでは、この値を設定することはできません)
-p 512 バイトブロック単位でのパイプのサイズ (これは設定で き
ないかもしれません)
-s 最大スタックサイズ
-t CPU 時間の最大量 (秒単位)
-u 1 人のユーザが使用できる最大のプロセス数
-v シェルが使用できる最大の仮想メモリ量
limit が与えられている場合、これは指定されたリソースの新しい値と
なります (-a は表示専用です)。オプションが全く与えられなかった場
合は、 -f が指定されたものと見なされます。値は 1024 バイト単位で
増えますが、例外として -t は秒単位、 -p 512 バイトブロック単位、
-n および -u は単位無しの値です。返却ステータスは基本的に 0 です
が、不正なオプションがある場合、 unlimited 以外の数字でない引 き
数 が limit に指定された場合、新しい制限を設定する際にエラーが起
きた場合は除きます。
umask [-p] [-S] [mode]
ユーザのファイル生成マスクに mode を設定します。 mode が数字で始
まる場合には、これは 10 進数と解釈されます。それ以外の場合には、
chmod(1) に指定するのと同様のシンボリックなモードマスクと解釈 さ
れ ま す。 mode が省略されると、現在のマスクの値が出力されます。
-S オプションを指定すると、マスクはシンボリックな形式で表示さ れ
ます。デフルトの出力は 10 進の数値です。 -p オプションが指定され
、かつ mode が省略された場合、入力として再利用できる形式で出力が
行われます。モードが正常に変更できた場合や、 mode 引き数が全く与
えられなかった場合には、返却ステータスは 0 となります。それ以 外
の場合には偽となります。
unalias [-a] [name ...]
name を定義されているエイリアスのリストから削除します。 -a が与
えられている場合には、エイリアス定義は全て削除されます。与えられ
た name が定義されているエイリアスであれば、返却ステータスは真に
なります。
unset [-fv] [name ...]
name それぞれについて、対応する変数や関数を削除します。オプシ ョ
ンが全く与えられていない場合や、 -v オプションが与えられた場合は
、各 name はシェル変数を参照します。読み込み専用の変数の設定を消
すことはできません。 -f が指定されている場合、各 name はシェル関
数を参照し、その関数の定義が削除されます。設定が消された変数や関
数は全て、それ以降のコマンドに渡される環境変数からも削除されます
。 RANDOM, SECONDS, LINENO, HISTCMD, FUNCNAME, GROUPS, DIRSTACK
のいずれかの設定を消した場合、これらの特殊な特性も無くなります。
これは後で再設定しても元に戻ることはありません。 name が存在しな
いか、読み込み専用の場合以外には、終了ステータスは真となります。
wait [n]
指定されたプロセスを wait し、その終了ステータスを返します 。 n
はプロセス ID またはジョブ指定です。ジョブ指定を与えた場合、その
ジョブのパイプラインに含まれる全てのプロセスを wait します 。 n
が 与 えられていない場合には、現在アクティブな全ての子プロセスを
wait し、返却ステータスは 0 となります。 n が存在しないプロセ ス
や ジョブを指定している場合、返却ステータスは 127 になります。そ
れ以外の場合、返却ステータスは wait していた最後のプロセスまたは
ジョブの終了ステータスとなります。
制限付きのシェル(RESTRICTED SHELL)
bash を rbash という名前で起動した場合や、起動時に -r オプションを指定
した場合には、シェルは制限された状態になります。制限付きのシェルは、 標
準 のシェルよりも細かく制御された環境を設定したいときに用います。制限付
きのシェルは bash と全く同じように動作しますが、以下のようなことが許 可
されなかったり実行されなかったりします:
· cd を使ってディレクトリを変更すること
· SHELL, PATH, ENV, BASH_ENV の値の設定や設定取り消しを行なうこと
· / を含むコマンド名を指定すること
· 組み込みコマンド . の引き数として / を含むファイル名を指定する
こと
· 組み込みコマンド hash に対するオプション -p の引数として / を 含
むファイル名を指定すること
· 起動時にシェル環境から関数定義をインポートすること
· 起動時にシェル環境から SHELLOPTS の値を展開すること
· リダイレクション演算子 >, >|, <>, >&, &>, >> を使ってリダイレク
トを行なうこと
· 組み込みコマンド exec を用いて、シェルを別のコマンドに置き換える
こと
· 組み込みコマンド enable に対する -f オプションと -d オプションを
使って、組み込みコマンドを追加・削除すること
· 組み込みコマンド command に -p オプションを指定すること
· set +r や set +o restricted を用いて制限モードを解除すること
これらの制限は、何らかの起動ファイルを読み込んだ後に適用されます。
シェルスクリプトであると判明したファイルが実行された時 (前述の コマンド
の実行を参照) には、 rbash はスクリプト実行用に立ち上げたシェルでは制限
を全て無効にします。
関連項目
Bash Reference Manual, Brian Fox and Chet Ramey
The Gnu Readline Library, Brian Fox and Chet Ramey
The Gnu History Library, Brian Fox and Chet Ramey
Portable Operating System Interface (POSIX) Part 2: Shell and Utili-
ties, IEEE
sh(1), ksh(1), csh(1)
emacs(1), vi(1)
readline(3)
ファイル
/bin/bash
bash の実行ファイル。
/etc/profile
システム全体用の初期化ファイル。ログインシェルが実行します。
~/.bash_profile
個人用の初期化ファイル。ログインシェルが実行します。
~/.bashrc
対話シェルごとに実行される、個人用の起動ファイル。
~/.bash_logout
個人用のログインシェル後処理ファイル。ログインシェルの終了時に実
行されます。
~/.inputrc
個人用の readline 初期化ファイル。
著者
Brian Fox, Free Software Foundation
bfox@gnu.org
Chet Ramey, Case Western Reserve University
chet@ins.CWRU.Edu
バグ報告
bash のバグを見つけたら必ず報告してください。ただし報告の前には、それが
本当にバグであることと、バグが最新版の bash で起こることを確かめてく だ
さい。
本当にバグがあると判断した場合には、 bashbug コマンドを使ってバグ報告を
行います。バグを修正してくださった場合には、ぜひその内容も一緒にメー ル
し てください! 提案や「哲学上の」バグ報告は、bug-bash@gnu.org にメール
したり、ニュースグループの gnu.bash.bug に投稿してくださっても構いま せ
ん。
バグ報告には必ず以下のことを書いてください:
bash のバージョン
ハードウェアとオペレーティングシステム
コンパイルに使ったコンパイラ
バグ動作の説明
バグを再現できる簡単なシェルスクリプトまたは「レシピ」
bashbug コマンドは、バグ報告を送るために用意されているテンプレートに、
最初の 3 項目を自動的に書き込みます。
このオンラインマニュアルに関するコメントやバグ報告は chet@ins.CWRU.Edu
宛にお願いします。
バグ
bash は大きすぎるし、遅すぎます。
bash と昔ながらのバージョンの sh にはちょっとした違いがいくつかあります
。この大部分は POSIX の仕様のせいで生じたものです。
使い方によっては、エイリアスは混乱の元になります。
シェル組み込みコマンドとシェル関数は停止・再実行できません。
複合コマンドや ‘a ; b ; c’ の形式のコマンド列は、プロセスのサスペンドを
行 う際に綺麗に扱うことができません。プロセスを停止すると、シェルはコマ
ンド列の次のコマンドを即座に実行するからです。この問題はコマンド列を 括
弧 の中に置いてサブシェルに実行させることで解決できます。こうすれば、ひ
とまとまりのものとして停止できます。
$(...) を使ったコマンド置換の内部にあるコマンドは、置換が実行される 時
ま で展開されません。これにより、コマンドを入力してしばらく経つまでエラ
ー出力が遅れます。
配列変数は (まだ) エクスポートできません。
複数のループの中で break または continue を実行した時に、最も外側のルー
プが一つ以上のコマンドを含んでいるなら、 break または continue の返り値
は失われる。
GNU Bash-2.05 2001 Mar 5 BASH(1)
BASH(1) BASH(1)
NAME
bash - GNU Bourne-Again SHell
SYNOPSIS
bash [options] [file]
COPYRIGHT
Bash is Copyright (C) 1989-2009 by the Free Software Foundation, Inc.
DESCRIPTION
Bash is an sh-compatible command language interpreter that executes
commands read from the standard input or from a file. Bash also incor-
porates useful features from the Korn and C shells (ksh and csh).
Bash is intended to be a conformant implementation of the Shell and
Utilities portion of the IEEE POSIX specification (IEEE Standard
1003.1). Bash can be configured to be POSIX-conformant by default.
OPTIONS
In addition to the single-character shell options documented in the
description of the set builtin command, bash interprets the following
options when it is invoked:
-c string If the -c option is present, then commands are read from
string. If there are arguments after the string, they are
assigned to the positional parameters, starting with $0.
-i If the -i option is present, the shell is interactive.
-l Make bash act as if it had been invoked as a login shell (see
INVOCATION below).
-r If the -r option is present, the shell becomes restricted
(see RESTRICTED SHELL below).
-s If the -s option is present, or if no arguments remain after
option processing, then commands are read from the standard
input. This option allows the positional parameters to be
set when invoking an interactive shell.
-D A list of all double-quoted strings preceded by $ is printed
on the standard output. These are the strings that are sub-
ject to language translation when the current locale is not C
or POSIX. This implies the -n option; no commands will be
executed.
[-+]O [shopt_option]
shopt_option is one of the shell options accepted by the
shopt builtin (see SHELL BUILTIN COMMANDS below). If
shopt_option is present, -O sets the value of that option; +O
unsets it. If shopt_option is not supplied, the names and
values of the shell options accepted by shopt are printed on
the standard output. If the invocation option is +O, the
output is displayed in a format that may be reused as input.
-- A -- signals the end of options and disables further option
processing. Any arguments after the -- are treated as file-
names and arguments. An argument of - is equivalent to --.
Bash also interprets a number of multi-character options. These
options must appear on the command line before the single-character
options to be recognized.
--debugger
Arrange for the debugger profile to be executed before the shell
starts. Turns on extended debugging mode (see the description
of the extdebug option to the shopt builtin below) and shell
function tracing (see the description of the -o functrace option
to the set builtin below).
--dump-po-strings
Equivalent to -D, but the output is in the GNU gettext po
(portable object) file format.
--dump-strings
Equivalent to -D.
--help Display a usage message on standard output and exit success-
fully.
--init-file file
--rcfile file
Execute commands from file instead of the standard personal ini-
tialization file ~/.bashrc if the shell is interactive (see
INVOCATION below).
--login
Equivalent to -l.
--noediting
Do not use the GNU readline library to read command lines when
the shell is interactive.
--noprofile
Do not read either the system-wide startup file /etc/profile or
any of the personal initialization files ~/.bash_profile,
~/.bash_login, or ~/.profile. By default, bash reads these
files when it is invoked as a login shell (see INVOCATION
below).
--norc Do not read and execute the personal initialization file
~/.bashrc if the shell is interactive. This option is on by
default if the shell is invoked as sh.
--posix
Change the behavior of bash where the default operation differs
from the POSIX standard to match the standard (posix mode).
--restricted
The shell becomes restricted (see RESTRICTED SHELL below).
--rpm-requires
Produce the list of files that are required for the shell script
to run. This implies ’-n’ and is subject to the same limita-
tions as compile time error checking checking; Backticks, []
tests, and evals are not parsed so some dependencies may be
missed.
--verbose
Equivalent to -v.
--version
Show version information for this instance of bash on the stan-
dard output and exit successfully.
ARGUMENTS
If arguments remain after option processing, and neither the -c nor the
-s option has been supplied, the first argument is assumed to be the
name of a file containing shell commands. If bash is invoked in this
fashion, $0 is set to the name of the file, and the positional parame-
ters are set to the remaining arguments. Bash reads and executes com-
mands from this file, then exits. Bash’s exit status is the exit sta-
tus of the last command executed in the script. If no commands are
executed, the exit status is 0. An attempt is first made to open the
file in the current directory, and, if no file is found, then the shell
searches the directories in PATH for the script.
INVOCATION
A login shell is one whose first character of argument zero is a -, or
one started with the --login option.
An interactive shell is one started without non-option arguments and
without the -c option whose standard input and error are both connected
to terminals (as determined by isatty(3)), or one started with the -i
option. PS1 is set and $- includes i if bash is interactive, allowing
a shell script or a startup file to test this state.
The following paragraphs describe how bash executes its startup files.
If any of the files exist but cannot be read, bash reports an error.
Tildes are expanded in file names as described below under Tilde Expan-
sion in the EXPANSION section.
When bash is invoked as an interactive login shell, or as a non-inter-
active shell with the --login option, it first reads and executes com-
mands from the file /etc/profile, if that file exists. After reading
that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile,
in that order, and reads and executes commands from the first one that
exists and is readable. The --noprofile option may be used when the
shell is started to inhibit this behavior.
When a login shell exits, bash reads and executes commands from the
files ~/.bash_logout and /etc/bash.bash_logout, if the files exists.
When an interactive shell that is not a login shell is started, bash
reads and executes commands from ~/.bashrc, if that file exists. This
may be inhibited by using the --norc option. The --rcfile file option
will force bash to read and execute commands from file instead of
~/.bashrc.
When bash is started non-interactively, to run a shell script, for
example, it looks for the variable BASH_ENV in the environment, expands
its value if it appears there, and uses the expanded value as the name
of a file to read and execute. Bash behaves as if the following com-
mand were executed:
if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
but the value of the PATH variable is not used to search for the file
name.
If bash is invoked with the name sh, it tries to mimic the startup
behavior of historical versions of sh as closely as possible, while
conforming to the POSIX standard as well. When invoked as an interac-
tive login shell, or a non-interactive shell with the --login option,
it first attempts to read and execute commands from /etc/profile and
~/.profile, in that order. The --noprofile option may be used to
inhibit this behavior. When invoked as an interactive shell with the
name sh, bash looks for the variable ENV, expands its value if it is
defined, and uses the expanded value as the name of a file to read and
execute. Since a shell invoked as sh does not attempt to read and exe-
cute commands from any other startup files, the --rcfile option has no
effect. A non-interactive shell invoked with the name sh does not
attempt to read any other startup files. When invoked as sh, bash
enters posix mode after the startup files are read.
When bash is started in posix mode, as with the --posix command line
option, it follows the POSIX standard for startup files. In this mode,
interactive shells expand the ENV variable and commands are read and
executed from the file whose name is the expanded value. No other
startup files are read.
Bash attempts to determine when it is being run with its standard input
connected to a a network connection, as if by the remote shell daemon,
usually rshd, or the secure shell daemon sshd. If bash determines it
is being run in this fashion, it reads and executes commands from
~/.bashrc, if that file exists and is readable. It will not do this if
invoked as sh. The --norc option may be used to inhibit this behavior,
and the --rcfile option may be used to force another file to be read,
but rshd does not generally invoke the shell with those options or
allow them to be specified.
If the shell is started with the effective user (group) id not equal to
the real user (group) id, and the -p option is not supplied, no startup
files are read, shell functions are not inherited from the environment,
the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables, if they
appear in the environment, are ignored, and the effective user id is
set to the real user id. If the -p option is supplied at invocation,
the startup behavior is the same, but the effective user id is not
reset.
DEFINITIONS
The following definitions are used throughout the rest of this docu-
ment.
blank A space or tab.
word A sequence of characters considered as a single unit by the
shell. Also known as a token.
name A word consisting only of alphanumeric characters and under-
scores, and beginning with an alphabetic character or an under-
score. Also referred to as an identifier.
metacharacter
A character that, when unquoted, separates words. One of the
following:
| & ; ( ) < > space tab
control operator
A token that performs a control function. It is one of the fol-
lowing symbols:
|| & && ; ;; ( ) | |&
RESERVED WORDS
Reserved words are words that have a special meaning to the shell. The
following words are recognized as reserved when unquoted and either the
first word of a simple command (see SHELL GRAMMAR below) or the third
word of a case or for command:
! case do done elif else esac fi for function if in select then until
while { } time [[ ]]
SHELL GRAMMAR
Simple Commands
A simple command is a sequence of optional variable assignments fol-
lowed by blank-separated words and redirections, and terminated by a
control operator. The first word specifies the command to be executed,
and is passed as argument zero. The remaining words are passed as
arguments to the invoked command.
The return value of a simple command is its exit status, or 128+n if
the command is terminated by signal n.
Pipelines
A pipeline is a sequence of one or more commands separated by one of
the control operators | or |&. The format for a pipeline is:
[time [-p]] [ ! ] command [ [|│|&] command2 ... ]
The standard output of command is connected via a pipe to the standard
input of command2. This connection is performed before any redirec-
tions specified by the command (see REDIRECTION below). If |& is used,
the standard error of command is connected to command2’s standard input
through the pipe; it is shorthand for 2>&1 |. This implicit redirec-
tion of the standard error is performed after any redirections speci-
fied by the command.
The return status of a pipeline is the exit status of the last command,
unless the pipefail option is enabled. If pipefail is enabled, the
pipeline’s return status is the value of the last (rightmost) command
to exit with a non-zero status, or zero if all commands exit
successfully. If the reserved word ! precedes a pipeline, the exit
status of that pipeline is the logical negation of the exit status as
described above. The shell waits for all commands in the pipeline to
terminate before returning a value.
If the time reserved word precedes a pipeline, the elapsed as well as
user and system time consumed by its execution are reported when the
pipeline terminates. The -p option changes the output format to that
specified by POSIX. The TIMEFORMAT variable may be set to a format
string that specifies how the timing information should be displayed;
see the description of TIMEFORMAT under Shell Variables below.
Each command in a pipeline is executed as a separate process (i.e., in
a subshell).
Lists
A list is a sequence of one or more pipelines separated by one of the
operators ;, &, &&, or ││, and optionally terminated by one of ;, &, or
.
Of these list operators, && and ││ have equal precedence, followed by ;
and &, which have equal precedence.
A sequence of one or more newlines may appear in a list instead of a
semicolon to delimit commands.
If a command is terminated by the control operator &, the shell exe-
cutes the command in the background in a subshell. The shell does not
wait for the command to finish, and the return status is 0. Commands
separated by a ; are executed sequentially; the shell waits for each
command to terminate in turn. The return status is the exit status of
the last command executed.
AND and OR lists are sequences of one of more pipelines separated by
the && and ││ control operators, respectively. AND and OR lists are
executed with left associativity. An AND list has the form
command1 && command2
command2 is executed if, and only if, command1 returns an exit status
of zero.
An OR list has the form
command1 ││ command2
command2 is executed if and only if command1 returns a non-zero exit
status. The return status of AND and OR lists is the exit status of
the last command executed in the list.
Compound Commands
A compound command is one of the following:
(list) list is executed in a subshell environment (see COMMAND EXECU-
TION ENVIRONMENT below). Variable assignments and builtin com-
mands that affect the shell’s environment do not remain in
effect after the command completes. The return status is the
exit status of list.
{ list; }
list is simply executed in the current shell environment. list
must be terminated with a newline or semicolon. This is known
as a group command. The return status is the exit status of
list. Note that unlike the metacharacters ( and ), { and } are
reserved words and must occur where a reserved word is permitted
to be recognized. Since they do not cause a word break, they
must be separated from list by whitespace or another shell
metacharacter.
((expression))
The expression is evaluated according to the rules described
below under ARITHMETIC EVALUATION. If the value of the expres-
sion is non-zero, the return status is 0; otherwise the return
status is 1. This is exactly equivalent to let "expression".
[[ expression ]]
Return a status of 0 or 1 depending on the evaluation of the
conditional expression expression. Expressions are composed of
the primaries described below under CONDITIONAL EXPRESSIONS.
Word splitting and pathname expansion are not performed on the
words between the [[ and ]]; tilde expansion, parameter and
variable expansion, arithmetic expansion, command substitution,
process substitution, and quote removal are performed. Condi-
tional operators such as -f must be unquoted to be recognized as
primaries.
When used with [[, The < and > operators sort lexicographically
using the current locale.
When the == and != operators are used, the string to the right
of the operator is considered a pattern and matched according to
the rules described below under Pattern Matching. If the shell
option nocasematch is enabled, the match is performed without
regard to the case of alphabetic characters. The return value
is 0 if the string matches (==) or does not match (!=) the pat-
tern, and 1 otherwise. Any part of the pattern may be quoted to
force it to be matched as a string.
An additional binary operator, =~, is available, with the same
precedence as == and !=. When it is used, the string to the
right of the operator is considered an extended regular expres-
sion and matched accordingly (as in regex(3)). The return value
is 0 if the string matches the pattern, and 1 otherwise. If the
regular expression is syntactically incorrect, the conditional
expression’s return value is 2. If the shell option nocasematch
is enabled, the match is performed without regard to the case of
alphabetic characters. Any part of the pattern may be quoted to
force it to be matched as a string. Substrings matched by
parenthesized subexpressions within the regular expression are
saved in the array variable BASH_REMATCH. The element of
BASH_REMATCH with index 0 is the portion of the string matching
the entire regular expression. The element of BASH_REMATCH with
index n is the portion of the string matching the nth parenthe-
sized subexpression.
Expressions may be combined using the following operators,
listed in decreasing order of precedence:
( expression )
Returns the value of expression. This may be used to
override the normal precedence of operators.
! expression
True if expression is false.
expression1 && expression2
True if both expression1 and expression2 are true.
expression1 || expression2
True if either expression1 or expression2 is true.
The && and || operators do not evaluate expression2 if the value
of expression1 is sufficient to determine the return value of
the entire conditional expression.
for name [ [ in [ word ... ] ] ; ] do list ; done
The list of words following in is expanded, generating a list of
items. The variable name is set to each element of this list in
turn, and list is executed each time. If the in word is omit-
ted, the for command executes list once for each positional
parameter that is set (see PARAMETERS below). The return status
is the exit status of the last command that executes. If the
expansion of the items following in results in an empty list, no
commands are executed, and the return status is 0.
for (( expr1 ; expr2 ; expr3 )) ; do list ; done
First, the arithmetic expression expr1 is evaluated according to
the rules described below under ARITHMETIC EVALUATION. The
arithmetic expression expr2 is then evaluated repeatedly until
it evaluates to zero. Each time expr2 evaluates to a non-zero
value, list is executed and the arithmetic expression expr3 is
evaluated. If any expression is omitted, it behaves as if it
evaluates to 1. The return value is the exit status of the last
command in list that is executed, or false if any of the expres-
sions is invalid.
select name [ in word ] ; do list ; done
The list of words following in is expanded, generating a list of
items. The set of expanded words is printed on the standard
error, each preceded by a number. If the in word is omitted,
the positional parameters are printed (see PARAMETERS below).
The PS3 prompt is then displayed and a line read from the stan-
dard input. If the line consists of a number corresponding to
one of the displayed words, then the value of name is set to
that word. If the line is empty, the words and prompt are dis-
played again. If EOF is read, the command completes. Any other
value read causes name to be set to null. The line read is
saved in the variable REPLY. The list is executed after each
selection until a break command is executed. The exit status of
select is the exit status of the last command executed in list,
or zero if no commands were executed.
case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
A case command first expands word, and tries to match it against
each pattern in turn, using the same matching rules as for path-
name expansion (see Pathname Expansion below). The word is
expanded using tilde expansion, parameter and variable expan-
sion, arithmetic substitution, command substitution, process
substitution and quote removal. Each pattern examined is
expanded using tilde expansion, parameter and variable expan-
sion, arithmetic substitution, command substitution, and process
substitution. If the shell option nocasematch is enabled, the
match is performed without regard to the case of alphabetic
characters. When a match is found, the corresponding list is
executed. If the ;; operator is used, no subsequent matches are
attempted after the first pattern match. Using ;& in place of
;; causes execution to continue with the list associated with
the next set of patterns. Using ;;& in place of ;; causes the
shell to test the next pattern list in the statement, if any,
and execute any associated list on a successful match. The exit
status is zero if no pattern matches. Otherwise, it is the exit
status of the last command executed in list.
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
The if list is executed. If its exit status is zero, the then
list is executed. Otherwise, each elif list is executed in
turn, and if its exit status is zero, the corresponding then
list is executed and the command completes. Otherwise, the else
list is executed, if present. The exit status is the exit sta-
tus of the last command executed, or zero if no condition tested
true.
while list; do list; done
until list; do list; done
The while command continuously executes the do list as long as
the last command in list returns an exit status of zero. The
until command is identical to the while command, except that the
test is negated; the do list is executed as long as the last
command in list returns a non-zero exit status. The exit status
of the while and until commands is the exit status of the last
do list command executed, or zero if none was executed.
Coprocesses
A coprocess is a shell command preceded by the coproc reserved word. A
coprocess is executed asynchronously in a subshell, as if the command
had been terminated with the & control operator, with a two-way pipe
established between the executing shell and the coprocess.
The format for a coprocess is:
coproc [NAME] command [redirections]
This creates a coprocess named NAME. If NAME is not supplied, the
default name is COPROC. NAME must not be supplied if command is a sim-
ple command (see above); otherwise, it is interpreted as the first word
of the simple command. When the coproc is executed, the shell creates
an array variable (see Arrays below) named NAME in the context of the
executing shell. The standard output of command is connected via a
pipe to a file descriptor in the executing shell, and that file
descriptor is assigned to NAME[0]. The standard input of command is
connected via a pipe to a file descriptor in the executing shell, and
that file descriptor is assigned to NAME[1]. This pipe is established
before any redirections specified by the command (see REDIRECTION
below). The file descriptors can be utilized as arguments to shell
commands and redirections using standard word expansions. The process
id of the shell spawned to execute the coprocess is available as the
value of the variable NAME_PID. The wait builtin command may be used
to wait for the coprocess to terminate.
The return status of a coprocess is the exit status of command.
Shell Function Definitions
A shell function is an object that is called like a simple command and
executes a compound command with a new set of positional parameters.
Shell functions are declared as follows:
[ function ] name () compound-command [redirection]
This defines a function named name. The reserved word function
is optional. If the function reserved word is supplied, the
parentheses are optional. The body of the function is the com-
pound command compound-command (see Compound Commands above).
That command is usually a list of commands between { and }, but
may be any command listed under Compound Commands above. com-
pound-command is executed whenever name is specified as the name
of a simple command. Any redirections (see REDIRECTION below)
specified when a function is defined are performed when the
function is executed. The exit status of a function definition
is zero unless a syntax error occurs or a readonly function with
the same name already exists. When executed, the exit status of
a function is the exit status of the last command executed in
the body. (See FUNCTIONS below.)
COMMENTS
In a non-interactive shell, or an interactive shell in which the inter-
active_comments option to the shopt builtin is enabled (see SHELL
BUILTIN COMMANDS below), a word beginning with # causes that word and
all remaining characters on that line to be ignored. An interactive
shell without the interactive_comments option enabled does not allow
comments. The interactive_comments option is on by default in interac-
tive shells.
QUOTING
Quoting is used to remove the special meaning of certain characters or
words to the shell. Quoting can be used to disable special treatment
for special characters, to prevent reserved words from being recognized
as such, and to prevent parameter expansion.
Each of the metacharacters listed above under DEFINITIONS has special
meaning to the shell and must be quoted if it is to represent itself.
When the command history expansion facilities are being used (see HIS-
TORY EXPANSION below), the history expansion character, usually !, must
be quoted to prevent history expansion.
There are three quoting mechanisms: the escape character, single
quotes, and double quotes.
A non-quoted backslash (\) is the escape character. It preserves the
literal value of the next character that follows, with the exception of
. If a \ pair appears, and the backslash is not
itself quoted, the \ is treated as a line continuation (that
is, it is removed from the input stream and effectively ignored).
Enclosing characters in single quotes preserves the literal value of
each character within the quotes. A single quote may not occur between
single quotes, even when preceded by a backslash.
Enclosing characters in double quotes preserves the literal value of
all characters within the quotes, with the exception of $, `, \, and,
when history expansion is enabled, !. The characters $ and ` retain
their special meaning within double quotes. The backslash retains its
special meaning only when followed by one of the following characters:
$, `, ", \, or . A double quote may be quoted within double
quotes by preceding it with a backslash. If enabled, history expansion
will be performed unless an ! appearing in double quotes is escaped
using a backslash. The backslash preceding the ! is not removed.
The special parameters * and @ have special meaning when in double
quotes (see PARAMETERS below).
Words of the form $'string' are treated specially. The word expands to
string, with backslash-escaped characters replaced as specified by the
ANSI C standard. Backslash escape sequences, if present, are decoded
as follows:
\a alert (bell)
\b backspace
\e
\E an escape character
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\' single quote
\" double quote
\nnn the eight-bit character whose value is the octal value
nnn (one to three digits)
\xHH the eight-bit character whose value is the hexadecimal
value HH (one or two hex digits)
\cx a control-x character
The expanded result is single-quoted, as if the dollar sign had not
been present.
A double-quoted string preceded by a dollar sign ($"string") will cause
the string to be translated according to the current locale. If the
current locale is C or POSIX, the dollar sign is ignored. If the
string is translated and replaced, the replacement is double-quoted.
PARAMETERS
A parameter is an entity that stores values. It can be a name, a num-
ber, or one of the special characters listed below under Special Param-
eters. A variable is a parameter denoted by a name. A variable has a
value and zero or more attributes. Attributes are assigned using the
declare builtin command (see declare below in SHELL BUILTIN COMMANDS).
A parameter is set if it has been assigned a value. The null string is
a valid value. Once a variable is set, it may be unset only by using
the unset builtin command (see SHELL BUILTIN COMMANDS below).
A variable may be assigned to by a statement of the form
name=[value]
If value is not given, the variable is assigned the null string. All
values undergo tilde expansion, parameter and variable expansion, com-
mand substitution, arithmetic expansion, and quote removal (see EXPAN-
SION below). If the variable has its integer attribute set, then value
is evaluated as an arithmetic expression even if the $((...)) expansion
is not used (see Arithmetic Expansion below). Word splitting is not
performed, with the exception of "$@" as explained below under Special
Parameters. Pathname expansion is not performed. Assignment state-
ments may also appear as arguments to the alias, declare, typeset,
export, readonly, and local builtin commands.
In the context where an assignment statement is assigning a value to a
shell variable or array index, the += operator can be used to append to
or add to the variable’s previous value. When += is applied to a vari-
able for which the integer attribute has been set, value is evaluated
as an arithmetic expression and added to the variable’s current value,
which is also evaluated. When += is applied to an array variable using
compound assignment (see Arrays below), the variable’s value is not
unset (as it is when using =), and new values are appended to the array
beginning at one greater than the array’s maximum index (for indexed
arrays) or added as additional key-value pairs in an associative array.
When applied to a string-valued variable, value is expanded and
appended to the variable’s value.
Positional Parameters
A positional parameter is a parameter denoted by one or more digits,
other than the single digit 0. Positional parameters are assigned from
the shell’s arguments when it is invoked, and may be reassigned using
the set builtin command. Positional parameters may not be assigned to
with assignment statements. The positional parameters are temporarily
replaced when a shell function is executed (see FUNCTIONS below).
When a positional parameter consisting of more than a single digit is
expanded, it must be enclosed in braces (see EXPANSION below).
Special Parameters
The shell treats several parameters specially. These parameters may
only be referenced; assignment to them is not allowed.
* Expands to the positional parameters, starting from one. When
the expansion occurs within double quotes, it expands to a sin-
gle word with the value of each parameter separated by the first
character of the IFS special variable. That is, "$*" is equiva-
lent to "$1c$2c...", where c is the first character of the value
of the IFS variable. If IFS is unset, the parameters are sepa-
rated by spaces. If IFS is null, the parameters are joined
without intervening separators.
@ Expands to the positional parameters, starting from one. When
the expansion occurs within double quotes, each parameter
expands to a separate word. That is, "$@" is equivalent to "$1"
"$2" ... If the double-quoted expansion occurs within a word,
the expansion of the first parameter is joined with the begin-
ning part of the original word, and the expansion of the last
parameter is joined with the last part of the original word.
When there are no positional parameters, "$@" and $@ expand to
nothing (i.e., they are removed).
# Expands to the number of positional parameters in decimal.
? Expands to the exit status of the most recently executed fore-
ground pipeline.
- Expands to the current option flags as specified upon invoca-
tion, by the set builtin command, or those set by the shell
itself (such as the -i option).
$ Expands to the process ID of the shell. In a () subshell, it
expands to the process ID of the current shell, not the sub-
shell.
! Expands to the process ID of the most recently executed back-
ground (asynchronous) command.
0 Expands to the name of the shell or shell script. This is set
at shell initialization. If bash is invoked with a file of com-
mands, $0 is set to the name of that file. If bash is started
with the -c option, then $0 is set to the first argument after
the string to be executed, if one is present. Otherwise, it is
set to the file name used to invoke bash, as given by argument
zero.
_ At shell startup, set to the absolute pathname used to invoke
the shell or shell script being executed as passed in the envi-
ronment or argument list. Subsequently, expands to the last
argument to the previous command, after expansion. Also set to
the full pathname used to invoke each command executed and
placed in the environment exported to that command. When check-
ing mail, this parameter holds the name of the mail file cur-
rently being checked.
Shell Variables
The following variables are set by the shell:
BASH Expands to the full file name used to invoke this instance of
bash.
BASHOPTS
A colon-separated list of enabled shell options. Each word in
the list is a valid argument for the -s option to the shopt
builtin command (see SHELL BUILTIN COMMANDS below). The options
appearing in BASHOPTS are those reported as on by shopt. If
this variable is in the environment when bash starts up, each
shell option in the list will be enabled before reading any
startup files. This variable is read-only.
BASHPID
Expands to the process id of the current bash process. This
differs from $$ under certain circumstances, such as subshells
that do not require bash to be re-initialized.
BASH_ALIASES
An associative array variable whose members correspond to the
internal list of aliases as maintained by the alias builtin Ele-
ments added to this array appear in the alias list; unsetting
array elements cause aliases to be removed from the alias list.
BASH_ARGC
An array variable whose values are the number of parameters in
each frame of the current bash execution call stack. The number
of parameters to the current subroutine (shell function or
script executed with . or source) is at the top of the stack.
When a subroutine is executed, the number of parameters passed
is pushed onto BASH_ARGC. The shell sets BASH_ARGC only when in
extended debugging mode (see the description of the extdebug
option to the shopt builtin below)
BASH_ARGV
An array variable containing all of the parameters in the cur-
rent bash execution call stack. The final parameter of the last
subroutine call is at the top of the stack; the first parameter
of the initial call is at the bottom. When a subroutine is exe-
cuted, the parameters supplied are pushed onto BASH_ARGV. The
shell sets BASH_ARGV only when in extended debugging mode (see
the description of the extdebug option to the shopt builtin
below)
BASH_CMDS
An associative array variable whose members correspond to the
internal hash table of commands as maintained by the hash
builtin. Elements added to this array appear in the hash table;
unsetting array elements cause commands to be removed from the
hash table.
BASH_COMMAND
The command currently being executed or about to be executed,
unless the shell is executing a command as the result of a trap,
in which case it is the command executing at the time of the
trap.
BASH_EXECUTION_STRING
The command argument to the -c invocation option.
BASH_LINENO
An array variable whose members are the line numbers in source
files corresponding to each member of FUNCNAME.
${BASH_LINENO[$i]} is the line number in the source file where
${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if refer-
enced within another shell function). The corresponding source
file name is ${BASH_SOURCE[$i]}. Use LINENO to obtain the cur-
rent line number.
BASH_REMATCH
An array variable whose members are assigned by the =~ binary
operator to the [[ conditional command. The element with index
0 is the portion of the string matching the entire regular
expression. The element with index n is the portion of the
string matching the nth parenthesized subexpression. This vari-
able is read-only.
BASH_SOURCE
An array variable whose members are the source filenames corre-
sponding to the elements in the FUNCNAME array variable.
BASH_SUBSHELL
Incremented by one each time a subshell or subshell environment
is spawned. The initial value is 0.
BASH_VERSINFO
A readonly array variable whose members hold version information
for this instance of bash. The values assigned to the array
members are as follows:
BASH_VERSINFO[0] The major version number (the release).
BASH_VERSINFO[1] The minor version number (the version).
BASH_VERSINFO[2] The patch level.
BASH_VERSINFO[3] The build version.
BASH_VERSINFO[4] The release status (e.g., beta1).
BASH_VERSINFO[5] The value of MACHTYPE.
BASH_VERSION
Expands to a string describing the version of this instance of
bash.
COMP_CWORD
An index into ${COMP_WORDS} of the word containing the current
cursor position. This variable is available only in shell func-
tions invoked by the programmable completion facilities (see
Programmable Completion below).
COMP_KEY
The key (or final key of a key sequence) used to invoke the cur-
rent completion function.
COMP_LINE
The current command line. This variable is available only in
shell functions and external commands invoked by the pro-
grammable completion facilities (see Programmable Completion
below).
COMP_POINT
The index of the current cursor position relative to the begin-
ning of the current command. If the current cursor position is
at the end of the current command, the value of this variable is
equal to ${#COMP_LINE}. This variable is available only in
shell functions and external commands invoked by the pro-
grammable completion facilities (see Programmable Completion
below).
COMP_TYPE
Set to an integer value corresponding to the type of completion
attempted that caused a completion function to be called: TAB,
for normal completion, ?, for listing completions after succes-
sive tabs, !, for listing alternatives on partial word comple-
tion, @, to list completions if the word is not unmodified, or
%, for menu completion. This variable is available only in
shell functions and external commands invoked by the pro-
grammable completion facilities (see Programmable Completion
below).
COMP_WORDBREAKS
The set of characters that the readline library treats as word
separators when performing word completion. If COMP_WORDBREAKS
is unset, it loses its special properties, even if it is subse-
quently reset.
COMP_WORDS
An array variable (see Arrays below) consisting of the individ-
ual words in the current command line. The line is split into
words as readline would split it, using COMP_WORDBREAKS as
described above. This variable is available only in shell func-
tions invoked by the programmable completion facilities (see
Programmable Completion below).
DIRSTACK
An array variable (see Arrays below) containing the current con-
tents of the directory stack. Directories appear in the stack
in the order they are displayed by the dirs builtin. Assigning
to members of this array variable may be used to modify directo-
ries already in the stack, but the pushd and popd builtins must
be used to add and remove directories. Assignment to this vari-
able will not change the current directory. If DIRSTACK is
unset, it loses its special properties, even if it is subse-
quently reset.
EUID Expands to the effective user ID of the current user, initial-
ized at shell startup. This variable is readonly.
FUNCNAME
An array variable containing the names of all shell functions
currently in the execution call stack. The element with index 0
is the name of any currently-executing shell function. The bot-
tom-most element is "main". This variable exists only when a
shell function is executing. Assignments to FUNCNAME have no
effect and return an error status. If FUNCNAME is unset, it
loses its special properties, even if it is subsequently reset.
GROUPS An array variable containing the list of groups of which the
current user is a member. Assignments to GROUPS have no effect
and return an error status. If GROUPS is unset, it loses its
special properties, even if it is subsequently reset.
HISTCMD
The history number, or index in the history list, of the current
command. If HISTCMD is unset, it loses its special properties,
even if it is subsequently reset.
HOSTNAME
Automatically set to the name of the current host.
HOSTTYPE
Automatically set to a string that uniquely describes the type
of machine on which bash is executing. The default is system-
dependent.
LINENO Each time this parameter is referenced, the shell substitutes a
decimal number representing the current sequential line number
(starting with 1) within a script or function. When not in a
script or function, the value substituted is not guaranteed to
be meaningful. If LINENO is unset, it loses its special proper-
ties, even if it is subsequently reset.
MACHTYPE
Automatically set to a string that fully describes the system
type on which bash is executing, in the standard GNU cpu-com-
pany-system format. The default is system-dependent.
OLDPWD The previous working directory as set by the cd command.
OPTARG The value of the last option argument processed by the getopts
builtin command (see SHELL BUILTIN COMMANDS below).
OPTIND The index of the next argument to be processed by the getopts
builtin command (see SHELL BUILTIN COMMANDS below).
OSTYPE Automatically set to a string that describes the operating sys-
tem on which bash is executing. The default is system-depen-
dent.
PIPESTATUS
An array variable (see Arrays below) containing a list of exit
status values from the processes in the most-recently-executed
foreground pipeline (which may contain only a single command).
PPID The process ID of the shell’s parent. This variable is read-
only.
PWD The current working directory as set by the cd command.
RANDOM Each time this parameter is referenced, a random integer between
0 and 32767 is generated. The sequence of random numbers may be
initialized by assigning a value to RANDOM. If RANDOM is unset,
it loses its special properties, even if it is subsequently
reset.
REPLY Set to the line of input read by the read builtin command when
no arguments are supplied.
SECONDS
Each time this parameter is referenced, the number of seconds
since shell invocation is returned. If a value is assigned to
SECONDS, the value returned upon subsequent references is the
number of seconds since the assignment plus the value assigned.
If SECONDS is unset, it loses its special properties, even if it
is subsequently reset.
SHELLOPTS
A colon-separated list of enabled shell options. Each word in
the list is a valid argument for the -o option to the set
builtin command (see SHELL BUILTIN COMMANDS below). The options
appearing in SHELLOPTS are those reported as on by set -o. If
this variable is in the environment when bash starts up, each
shell option in the list will be enabled before reading any
startup files. This variable is read-only.
SHLVL Incremented by one each time an instance of bash is started.
UID Expands to the user ID of the current user, initialized at shell
startup. This variable is readonly.
The following variables are used by the shell. In some cases, bash
assigns a default value to a variable; these cases are noted below.
BASH_ENV
If this parameter is set when bash is executing a shell script,
its value is interpreted as a filename containing commands to
initialize the shell, as in ~/.bashrc. The value of BASH_ENV is
subjected to parameter expansion, command substitution, and
arithmetic expansion before being interpreted as a file name.
PATH is not used to search for the resultant file name.
CDPATH The search path for the cd command. This is a colon-separated
list of directories in which the shell looks for destination
directories specified by the cd command. A sample value is
".:~:/usr".
BASH_XTRACEFD
If set to an integer corresponding to a valid file descriptor,
bash will write the trace output generated when set -x is
enabled to that file descriptor. The file descriptor is closed
when BASH_XTRACEFD is unset or assigned a new value. Unsetting
BASH_XTRACEFD or assigning it the empty string causes the trace
output to be sent to the standard error. Note that setting
BASH_XTRACEFD to 2 (the standard error file descriptor) and then
unsetting it will result in the standard error being closed.
COLUMNS
Used by the select builtin command to determine the terminal
width when printing selection lists. Automatically set upon
receipt of a SIGWINCH.
COMPREPLY
An array variable from which bash reads the possible completions
generated by a shell function invoked by the programmable com-
pletion facility (see Programmable Completion below).
EMACS If bash finds this variable in the environment when the shell
starts with value "t", it assumes that the shell is running in
an emacs shell buffer and disables line editing.
FCEDIT The default editor for the fc builtin command.
FIGNORE
A colon-separated list of suffixes to ignore when performing
filename completion (see READLINE below). A filename whose suf-
fix matches one of the entries in FIGNORE is excluded from the
list of matched filenames. A sample value is ".o:~".
GLOBIGNORE
A colon-separated list of patterns defining the set of filenames
to be ignored by pathname expansion. If a filename matched by a
pathname expansion pattern also matches one of the patterns in
GLOBIGNORE, it is removed from the list of matches.
HISTCONTROL
A colon-separated list of values controlling how commands are
saved on the history list. If the list of values includes
ignorespace, lines which begin with a space character are not
saved in the history list. A value of ignoredups causes lines
matching the previous history entry to not be saved. A value of
ignoreboth is shorthand for ignorespace and ignoredups. A value
of erasedups causes all previous lines matching the current line
to be removed from the history list before that line is saved.
Any value not in the above list is ignored. If HISTCONTROL is
unset, or does not include a valid value, all lines read by the
shell parser are saved on the history list, subject to the value
of HISTIGNORE. The second and subsequent lines of a multi-line
compound command are not tested, and are added to the history
regardless of the value of HISTCONTROL.
HISTFILE
The name of the file in which command history is saved (see HIS-
TORY below). The default value is ~/.bash_history. If unset,
the command history is not saved when an interactive shell
exits.
HISTFILESIZE
The maximum number of lines contained in the history file. When
this variable is assigned a value, the history file is trun-
cated, if necessary, by removing the oldest entries, to contain
no more than that number of lines. The default value is 500.
The history file is also truncated to this size after writing it
when an interactive shell exits.
HISTIGNORE
A colon-separated list of patterns used to decide which command
lines should be saved on the history list. Each pattern is
anchored at the beginning of the line and must match the com-
plete line (no implicit ‘*’ is appended). Each pattern is
tested against the line after the checks specified by HISTCON-
TROL are applied. In addition to the normal shell pattern
matching characters, ‘&’ matches the previous history line. ‘&’
may be escaped using a backslash; the backslash is removed
before attempting a match. The second and subsequent lines of a
multi-line compound command are not tested, and are added to the
history regardless of the value of HISTIGNORE.
HISTSIZE
The number of commands to remember in the command history (see
HISTORY below). The default value is 500.
HISTTIMEFORMAT
If this variable is set and not null, its value is used as a
format string for strftime(3) to print the time stamp associated
with each history entry displayed by the history builtin. If
this variable is set, time stamps are written to the history
file so they may be preserved across shell sessions. This uses
the history comment character to distinguish timestamps from
other history lines.
HOME The home directory of the current user; the default argument for
the cd builtin command. The value of this variable is also used
when performing tilde expansion.
HOSTFILE
Contains the name of a file in the same format as /etc/hosts
that should be read when the shell needs to complete a hostname.
The list of possible hostname completions may be changed while
the shell is running; the next time hostname completion is
attempted after the value is changed, bash adds the contents of
the new file to the existing list. If HOSTFILE is set, but has
no value, or does not name a readable file, bash attempts to
read /etc/hosts to obtain the list of possible hostname comple-
tions. When HOSTFILE is unset, the hostname list is cleared.
IFS The Internal Field Separator that is used for word splitting
after expansion and to split lines into words with the read
builtin command. The default value is ‘‘’’.
IGNOREEOF
Controls the action of an interactive shell on receipt of an EOF
character as the sole input. If set, the value is the number of
consecutive EOF characters which must be typed as the first
characters on an input line before bash exits. If the variable
exists but does not have a numeric value, or has no value, the
default value is 10. If it does not exist, EOF signifies the
end of input to the shell.
INPUTRC
The filename for the readline startup file, overriding the
default of ~/.inputrc (see READLINE below).
LANG Used to determine the locale category for any category not
specifically selected with a variable starting with LC_.
LC_ALL This variable overrides the value of LANG and any other LC_
variable specifying a locale category.
LC_COLLATE
This variable determines the collation order used when sorting
the results of pathname expansion, and determines the behavior
of range expressions, equivalence classes, and collating
sequences within pathname expansion and pattern matching.
LC_CTYPE
This variable determines the interpretation of characters and
the behavior of character classes within pathname expansion and
pattern matching.
LC_MESSAGES
This variable determines the locale used to translate double-
quoted strings preceded by a $.
LC_NUMERIC
This variable determines the locale category used for number
formatting.
LINES Used by the select builtin command to determine the column
length for printing selection lists. Automatically set upon
receipt of a SIGWINCH.
MAIL If this parameter is set to a file name and the MAILPATH vari-
able is not set, bash informs the user of the arrival of mail in
the specified file.
MAILCHECK
Specifies how often (in seconds) bash checks for mail. The
default is 60 seconds. When it is time to check for mail, the
shell does so before displaying the primary prompt. If this
variable is unset, or set to a value that is not a number
greater than or equal to zero, the shell disables mail checking.
MAILPATH
A colon-separated list of file names to be checked for mail.
The message to be printed when mail arrives in a particular file
may be specified by separating the file name from the message
with a ‘?’. When used in the text of the message, $_ expands to
the name of the current mailfile. Example:
MAILPATH='/var/mail/bfox?"You have mail":~/shell-mail?"$_ has
mail!"'
Bash supplies a default value for this variable, but the
location of the user mail files that it uses is system dependent
(e.g., /var/mail/$USER).
OPTERR If set to the value 1, bash displays error messages generated by
the getopts builtin command (see SHELL BUILTIN COMMANDS below).
OPTERR is initialized to 1 each time the shell is invoked or a
shell script is executed.
PATH The search path for commands. It is a colon-separated list of
directories in which the shell looks for commands (see COMMAND
EXECUTION below). A zero-length (null) directory name in the
value of PATH indicates the current directory. A null directory
name may appear as two adjacent colons, or as an initial or
trailing colon. The default path is system-dependent, and is
set by the administrator who installs bash. A common value is
‘‘/usr/gnu/bin:/usr/local/bin:/usr/ucb:/bin:/usr/bin’’.
POSIXLY_CORRECT
If this variable is in the environment when bash starts, the
shell enters posix mode before reading the startup files, as if
the --posix invocation option had been supplied. If it is set
while the shell is running, bash enables posix mode, as if the
command set -o posix had been executed.
PROMPT_COMMAND
If set, the value is executed as a command prior to issuing each
primary prompt.
PROMPT_DIRTRIM
If set to a number greater than zero, the value is used as the
number of trailing directory components to retain when expanding
the \w and \W prompt string escapes (see PROMPTING below).
Characters removed are replaced with an ellipsis.
PS1 The value of this parameter is expanded (see PROMPTING below)
and used as the primary prompt string. The default value is
‘‘\s-\v\$ ’’.
PS2 The value of this parameter is expanded as with PS1 and used as
the secondary prompt string. The default is ‘‘> ’’.
PS3 The value of this parameter is used as the prompt for the select
command (see SHELL GRAMMAR above).
PS4 The value of this parameter is expanded as with PS1 and the
value is printed before each command bash displays during an
execution trace. The first character of PS4 is replicated mul-
tiple times, as necessary, to indicate multiple levels of indi-
rection. The default is ‘‘+ ’’.
SHELL The full pathname to the shell is kept in this environment vari-
able. If it is not set when the shell starts, bash assigns to
it the full pathname of the current user’s login shell.
TIMEFORMAT
The value of this parameter is used as a format string specify-
ing how the timing information for pipelines prefixed with the
time reserved word should be displayed. The % character intro-
duces an escape sequence that is expanded to a time value or
other information. The escape sequences and their meanings are
as follows; the braces denote optional portions.
%% A literal %.
%[p][l]R The elapsed time in seconds.
%[p][l]U The number of CPU seconds spent in user mode.
%[p][l]S The number of CPU seconds spent in system mode.
%P The CPU percentage, computed as (%U + %S) / %R.
The optional p is a digit specifying the precision, the number
of fractional digits after a decimal point. A value of 0 causes
no decimal point or fraction to be output. At most three places
after the decimal point may be specified; values of p greater
than 3 are changed to 3. If p is not specified, the value 3 is
used.
The optional l specifies a longer format, including minutes, of
the form MMmSS.FFs. The value of p determines whether or not
the fraction is included.
If this variable is not set, bash acts as if it had the value
$'\nreal\t%3lR\nuser\t%3lU\nsys%3lS'. If the value is null, no
timing information is displayed. A trailing newline is added
when the format string is displayed.
TMOUT If set to a value greater than zero, TMOUT is treated as the
default timeout for the read builtin. The select command
terminates if input does not arrive after TMOUT seconds when
input is coming from a terminal. In an interactive shell, the
value is interpreted as the number of seconds to wait for input
after issuing the primary prompt. Bash terminates after waiting
for that number of seconds if input does not arrive.
TMPDIR If set, Bash uses its value as the name of a directory in which
Bash creates temporary files for the shell’s use.
auto_resume
This variable controls how the shell interacts with the user and
job control. If this variable is set, single word simple com-
mands without redirections are treated as candidates for resump-
tion of an existing stopped job. There is no ambiguity allowed;
if there is more than one job beginning with the string typed,
the job most recently accessed is selected. The name of a
stopped job, in this context, is the command line used to start
it. If set to the value exact, the string supplied must match
the name of a stopped job exactly; if set to substring, the
string supplied needs to match a substring of the name of a
stopped job. The substring value provides functionality analo-
gous to the %? job identifier (see JOB CONTROL below). If set
to any other value, the supplied string must be a prefix of a
stopped job’s name; this provides functionality analogous to the
%string job identifier.
histchars
The two or three characters which control history expansion and
tokenization (see HISTORY EXPANSION below). The first character
is the history expansion character, the character which signals
the start of a history expansion, normally ‘!’. The second
character is the quick substitution character, which is used as
shorthand for re-running the previous command entered, substi-
tuting one string for another in the command. The default is
‘^’. The optional third character is the character which indi-
cates that the remainder of the line is a comment when found as
the first character of a word, normally ‘#’. The history com-
ment character causes history substitution to be skipped for the
remaining words on the line. It does not necessarily cause the
shell parser to treat the rest of the line as a comment.
Arrays
Bash provides one-dimensional indexed and associative array variables.
Any variable may be used as an indexed array; the declare builtin will
explicitly declare an array. There is no maximum limit on the size of
an array, nor any requirement that members be indexed or assigned con-
tiguously. Indexed arrays are referenced using integers (including
arithmetic expressions) and are zero-based; associative arrays are
referenced using arbitrary strings.
An indexed array is created automatically if any variable is assigned
to using the syntax name[subscript]=value. The subscript is treated as
an arithmetic expression that must evaluate to a number greater than or
equal to zero. To explicitly declare an indexed array, use declare -a
name (see SHELL BUILTIN COMMANDS below). declare -a name[subscript] is
also accepted; the subscript is ignored.
Associative arrays are created using declare -A name.
Attributes may be specified for an array variable using the declare and
readonly builtins. Each attribute applies to all members of an array.
Arrays are assigned to using compound assignments of the form
name=(value1 ... valuen), where each value is of the form [sub-
script]=string. Indexed array assignments do not require the bracket
and subscript. When assigning to indexed arrays, if the optional
brackets and subscript are supplied, that index is assigned to; other-
wise the index of the element assigned is the last index assigned to by
the statement plus one. Indexing starts at zero.
When assigning to an associative array, the subscript is required.
This syntax is also accepted by the declare builtin. Individual array
elements may be assigned to using the name[subscript]=value syntax
introduced above.
Any element of an array may be referenced using ${name[subscript]}.
The braces are required to avoid conflicts with pathname expansion. If
subscript is @ or *, the word expands to all members of name. These
subscripts differ only when the word appears within double quotes. If
the word is double-quoted, ${name[*]} expands to a single word with the
value of each array member separated by the first character of the IFS
special variable, and ${name[@]} expands each element of name to a sep-
arate word. When there are no array members, ${name[@]} expands to
nothing. If the double-quoted expansion occurs within a word, the
expansion of the first parameter is joined with the beginning part of
the original word, and the expansion of the last parameter is joined
with the last part of the original word. This is analogous to the
expansion of the special parameters * and @ (see Special Parameters
above). ${#name[subscript]} expands to the length of ${name[sub-
script]}. If subscript is * or @, the expansion is the number of ele-
ments in the array. Referencing an array variable without a subscript
is equivalent to referencing the array with a subscript of 0.
An array variable is considered set if a subscript has been assigned a
value. The null string is a valid value.
The unset builtin is used to destroy arrays. unset name[subscript]
destroys the array element at index subscript. Care must be taken to
avoid unwanted side effects caused by pathname expansion. unset name,
where name is an array, or unset name[subscript], where subscript is *
or @, removes the entire array.
The declare, local, and readonly builtins each accept a -a option to
specify an indexed array and a -A option to specify an associative
array. The read builtin accepts a -a option to assign a list of words
read from the standard input to an array. The set and declare builtins
display array values in a way that allows them to be reused as assign-
ments.
EXPANSION
Expansion is performed on the command line after it has been split into
words. There are seven kinds of expansion performed: brace expansion,
tilde expansion, parameter and variable expansion, command substitu-
tion, arithmetic expansion, word splitting, and pathname expansion.
The order of expansions is: brace expansion, tilde expansion, parame-
ter, variable and arithmetic expansion and command substitution (done
in a left-to-right fashion), word splitting, and pathname expansion.
On systems that can support it, there is an additional expansion avail-
able: process substitution.
Only brace expansion, word splitting, and pathname expansion can change
the number of words of the expansion; other expansions expand a single
word to a single word. The only exceptions to this are the expansions
of "$@" and "${name[@]}" as explained above (see PARAMETERS).
Brace Expansion
Brace expansion is a mechanism by which arbitrary strings may be gener-
ated. This mechanism is similar to pathname expansion, but the file-
names generated need not exist. Patterns to be brace expanded take the
form of an optional preamble, followed by either a series of comma-sep-
arated strings or a sequence expression between a pair of braces, fol-
lowed by an optional postscript. The preamble is prefixed to each
string contained within the braces, and the postscript is then appended
to each resulting string, expanding left to right.
Brace expansions may be nested. The results of each expanded string
are not sorted; left to right order is preserved. For example,
a{d,c,b}e expands into ‘ade ace abe’.
A sequence expression takes the form {x..y[..incr]}, where x and y are
either integers or single characters, and incr, an optional increment,
is an integer. When integers are supplied, the expression expands to
each number between x and y, inclusive. Supplied integers may be pre-
fixed with 0 to force each term to have the same width. When either x
or y begins with a zero, the shell attempts to force all generated
terms to contain the same number of digits, zero-padding where neces-
sary. When characters are supplied, the expression expands to each
character lexicographically between x and y, inclusive. Note that both
x and y must be of the same type. When the increment is supplied, it
is used as the difference between each term. The default increment is
1 or -1 as appropriate.
Brace expansion is performed before any other expansions, and any char-
acters special to other expansions are preserved in the result. It is
strictly textual. Bash does not apply any syntactic interpretation to
the context of the expansion or the text between the braces.
A correctly-formed brace expansion must contain unquoted opening and
closing braces, and at least one unquoted comma or a valid sequence
expression. Any incorrectly formed brace expansion is left unchanged.
A { or , may be quoted with a backslash to prevent its being considered
part of a brace expression. To avoid conflicts with parameter expan-
sion, the string ${ is not considered eligible for brace expansion.
This construct is typically used as shorthand when the common prefix of
the strings to be generated is longer than in the above example:
mkdir /usr/local/src/bash/{old,new,dist,bugs}
or
chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
Brace expansion introduces a slight incompatibility with historical
versions of sh. sh does not treat opening or closing braces specially
when they appear as part of a word, and preserves them in the output.
Bash removes braces from words as a consequence of brace expansion.
For example, a word entered to sh as file{1,2} appears identically in
the output. The same word is output as file1 file2 after expansion by
bash. If strict compatibility with sh is desired, start bash with the
+B option or disable brace expansion with the +B option to the set com-
mand (see SHELL BUILTIN COMMANDS below).
Tilde Expansion
If a word begins with an unquoted tilde character (‘~’), all of the
characters preceding the first unquoted slash (or all characters, if
there is no unquoted slash) are considered a tilde-prefix. If none of
the characters in the tilde-prefix are quoted, the characters in the
tilde-prefix following the tilde are treated as a possible login name.
If this login name is the null string, the tilde is replaced with the
value of the shell parameter HOME. If HOME is unset, the home direc-
tory of the user executing the shell is substituted instead. Other-
wise, the tilde-prefix is replaced with the home directory associated
with the specified login name.
If the tilde-prefix is a ‘~+’, the value of the shell variable PWD
replaces the tilde-prefix. If the tilde-prefix is a ‘~-’, the value of
the shell variable OLDPWD, if it is set, is substituted. If the char-
acters following the tilde in the tilde-prefix consist of a number N,
optionally prefixed by a ‘+’ or a ‘-’, the tilde-prefix is replaced
with the corresponding element from the directory stack, as it would be
displayed by the dirs builtin invoked with the tilde-prefix as an argu-
ment. If the characters following the tilde in the tilde-prefix con-
sist of a number without a leading ‘+’ or ‘-’, ‘+’ is assumed.
If the login name is invalid, or the tilde expansion fails, the word is
unchanged.
Each variable assignment is checked for unquoted tilde-prefixes immedi-
ately following a : or the first =. In these cases, tilde expansion is
also performed. Consequently, one may use file names with tildes in
assignments to PATH, MAILPATH, and CDPATH, and the shell assigns the
expanded value.
Parameter Expansion
The ‘$’ character introduces parameter expansion, command substitution,
or arithmetic expansion. The parameter name or symbol to be expanded
may be enclosed in braces, which are optional but serve to protect the
variable to be expanded from characters immediately following it which
could be interpreted as part of the name.
When braces are used, the matching ending brace is the first ‘}’ not
escaped by a backslash or within a quoted string, and not within an
embedded arithmetic expansion, command substitution, or parameter
expansion.
${parameter}
The value of parameter is substituted. The braces are required
when parameter is a positional parameter with more than one
digit, or when parameter is followed by a character which is not
to be interpreted as part of its name.
If the first character of parameter is an exclamation point (!), a
level of variable indirection is introduced. Bash uses the value of
the variable formed from the rest of parameter as the name of the vari-
able; this variable is then expanded and that value is used in the rest
of the substitution, rather than the value of parameter itself. This
is known as indirect expansion. The exceptions to this are the expan-
sions of ${!prefix*} and ${!name[@]} described below. The exclamation
point must immediately follow the left brace in order to introduce
indirection.
In each of the cases below, word is subject to tilde expansion, parame-
ter expansion, command substitution, and arithmetic expansion.
When not performing substring expansion, using the forms documented
below, bash tests for a parameter that is unset or null. Omitting the
colon results in a test only for a parameter that is unset.
${parameter:-word}
Use Default Values. If parameter is unset or null, the expan-
sion of word is substituted. Otherwise, the value of parameter
is substituted.
${parameter:=word}
Assign Default Values. If parameter is unset or null, the
expansion of word is assigned to parameter. The value of param-
eter is then substituted. Positional parameters and special
parameters may not be assigned to in this way.
${parameter:?word}
Display Error if Null or Unset. If parameter is null or unset,
the expansion of word (or a message to that effect if word is
not present) is written to the standard error and the shell, if
it is not interactive, exits. Otherwise, the value of parameter
is substituted.
${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing is
substituted, otherwise the expansion of word is substituted.
${parameter:offset}
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of
parameter starting at the character specified by offset. If
length is omitted, expands to the substring of parameter start-
ing at the character specified by offset. length and offset are
arithmetic expressions (see ARITHMETIC EVALUATION below).
length must evaluate to a number greater than or equal to zero.
If offset evaluates to a number less than zero, the value is
used as an offset from the end of the value of parameter. If
parameter is @, the result is length positional parameters
beginning at offset. If parameter is an indexed array name sub-
scripted by @ or *, the result is the length members of the
array beginning with ${parameter[offset]}. A negative offset is
taken relative to one greater than the maximum index of the
specified array. Substring expansion applied to an associative
array produces undefined results. Note that a negative offset
must be separated from the colon by at least one space to avoid
being confused with the :- expansion. Substring indexing is
zero-based unless the positional parameters are used, in which
case the indexing starts at 1 by default. If offset is 0, and
the positional parameters are used, $0 is prefixed to the list.
${!prefix*}
${!prefix@}
Names matching prefix. Expands to the names of variables whose
names begin with prefix, separated by the first character of the
IFS special variable. When @ is used and the expansion appears
within double quotes, each variable name expands to a separate
word.
${!name[@]}
${!name[*]}
List of array keys. If name is an array variable, expands to
the list of array indices (keys) assigned in name. If name is
not an array, expands to 0 if name is set and null otherwise.
When @ is used and the expansion appears within double quotes,
each key expands to a separate word.
${#parameter}
Parameter length. The length in characters of the value of
parameter is substituted. If parameter is * or @, the value
substituted is the number of positional parameters. If parame-
ter is an array name subscripted by * or @, the value substi-
tuted is the number of elements in the array.
${parameter#word}
${parameter##word}
Remove matching prefix pattern. The word is expanded to produce
a pattern just as in pathname expansion. If the pattern matches
the beginning of the value of parameter, then the result of the
expansion is the expanded value of parameter with the shortest
matching pattern (the ‘‘#’’ case) or the longest matching pat-
tern (the ‘‘##’’ case) deleted. If parameter is @ or *, the
pattern removal operation is applied to each positional parame-
ter in turn, and the expansion is the resultant list. If param-
eter is an array variable subscripted with @ or *, the pattern
removal operation is applied to each member of the array in
turn, and the expansion is the resultant list.
${parameter%word}
${parameter%%word}
Remove matching suffix pattern. The word is expanded to produce
a pattern just as in pathname expansion. If the pattern matches
a trailing portion of the expanded value of parameter, then the
result of the expansion is the expanded value of parameter with
the shortest matching pattern (the ‘‘%’’ case) or the longest
matching pattern (the ‘‘%%’’ case) deleted. If parameter is @
or *, the pattern removal operation is applied to each posi-
tional parameter in turn, and the expansion is the resultant
list. If parameter is an array variable subscripted with @ or
*, the pattern removal operation is applied to each member of
the array in turn, and the expansion is the resultant list.
${parameter/pattern/string}
Pattern substitution. The pattern is expanded to produce a pat-
tern just as in pathname expansion. Parameter is expanded and
the longest match of pattern against its value is replaced with
string. If pattern begins with /, all matches of pattern are
replaced with string. Normally only the first match is
replaced. If pattern begins with #, it must match at the begin-
ning of the expanded value of parameter. If pattern begins with
%, it must match at the end of the expanded value of parameter.
If string is null, matches of pattern are deleted and the / fol-
lowing pattern may be omitted. If parameter is @ or *, the sub-
stitution operation is applied to each positional parameter in
turn, and the expansion is the resultant list. If parameter is
an array variable subscripted with @ or *, the substitution
operation is applied to each member of the array in turn, and
the expansion is the resultant list.
${parameter^pattern}
${parameter^^pattern}
${parameter,pattern}
${parameter,,pattern}
Case modification. This expansion modifies the case of alpha-
betic characters in parameter. The pattern is expanded to pro-
duce a pattern just as in pathname expansion. The ^ operator
converts lowercase letters matching pattern to uppercase; the ,
operator converts matching uppercase letters to lowercase. The
^^ and ,, expansions convert each matched character in the
expanded value; the ^ and , expansions match and convert only
the first character in the expanded value.. If pattern is omit-
ted, it is treated like a ?, which matches every character. If
parameter is @ or *, the case modification operation is applied
to each positional parameter in turn, and the expansion is the
resultant list. If parameter is an array variable subscripted
with @ or *, the case modification operation is applied to each
member of the array in turn, and the expansion is the resultant
list.
Command Substitution
Command substitution allows the output of a command to replace the com-
mand name. There are two forms:
$(command)
or
`command`
Bash performs the expansion by executing command and replacing the com-
mand substitution with the standard output of the command, with any
trailing newlines deleted. Embedded newlines are not deleted, but they
may be removed during word splitting. The command substitution $(cat
file) can be replaced by the equivalent but faster $(< file).
When the old-style backquote form of substitution is used, backslash
retains its literal meaning except when followed by $, `, or \. The
first backquote not preceded by a backslash terminates the command sub-
stitution. When using the $(command) form, all characters between the
parentheses make up the command; none are treated specially.
Command substitutions may be nested. To nest when using the backquoted
form, escape the inner backquotes with backslashes.
If the substitution appears within double quotes, word splitting and
pathname expansion are not performed on the results.
Arithmetic Expansion
Arithmetic expansion allows the evaluation of an arithmetic expression
and the substitution of the result. The format for arithmetic expan-
sion is:
$((expression))
The expression is treated as if it were within double quotes, but a
double quote inside the parentheses is not treated specially. All
tokens in the expression undergo parameter expansion, string expansion,
command substitution, and quote removal. Arithmetic expansions may be
nested.
The evaluation is performed according to the rules listed below under
ARITHMETIC EVALUATION. If expression is invalid, bash prints a message
indicating failure and no substitution occurs.
Process Substitution
Process substitution is supported on systems that support named pipes
(FIFOs) or the /dev/fd method of naming open files. It takes the form
of <(list) or >(list). The process list is run with its input or out-
put connected to a FIFO or some file in /dev/fd. The name of this file
is passed as an argument to the current command as the result of the
expansion. If the >(list) form is used, writing to the file will pro-
vide input for list. If the <(list) form is used, the file passed as
an argument should be read to obtain the output of list.
When available, process substitution is performed simultaneously with
parameter and variable expansion, command substitution, and arithmetic
expansion.
Word Splitting
The shell scans the results of parameter expansion, command substitu-
tion, and arithmetic expansion that did not occur within double quotes
for word splitting.
The shell treats each character of IFS as a delimiter, and splits the
results of the other expansions into words on these characters. If IFS
is unset, or its value is exactly , the default,
then sequences of , , and at the beginning and
end of the results of the previous expansions are ignored, and any
sequence of IFS characters not at the beginning or end serves to
delimit words. If IFS has a value other than the default, then
sequences of the whitespace characters space and tab are ignored at the
beginning and end of the word, as long as the whitespace character is
in the value of IFS (an IFS whitespace character). Any character in
IFS that is not IFS whitespace, along with any adjacent IFS whitespace
characters, delimits a field. A sequence of IFS whitespace characters
is also treated as a delimiter. If the value of IFS is null, no word
splitting occurs.
Explicit null arguments ("" or '') are retained. Unquoted implicit
null arguments, resulting from the expansion of parameters that have no
values, are removed. If a parameter with no value is expanded within
double quotes, a null argument results and is retained.
Note that if no expansion occurs, no splitting is performed.
Pathname Expansion
After word splitting, unless the -f option has been set, bash scans
each word for the characters *, ?, and [. If one of these characters
appears, then the word is regarded as a pattern, and replaced with an
alphabetically sorted list of file names matching the pattern. If no
matching file names are found, and the shell option nullglob is not
enabled, the word is left unchanged. If the nullglob option is set,
and no matches are found, the word is removed. If the failglob shell
option is set, and no matches are found, an error message is printed
and the command is not executed. If the shell option nocaseglob is
enabled, the match is performed without regard to the case of alpha-
betic characters. When a pattern is used for pathname expansion, the
character ‘‘.’’ at the start of a name or immediately following a
slash must be matched explicitly, unless the shell option dotglob is
set. When matching a pathname, the slash character must always be
matched explicitly. In other cases, the ‘‘.’’ character is not
treated specially. See the description of shopt below under SHELL
BUILTIN COMMANDS for a description of the nocaseglob, nullglob, fail-
glob, and dotglob shell options.
The GLOBIGNORE shell variable may be used to restrict the set of file
names matching a pattern. If GLOBIGNORE is set, each matching file
name that also matches one of the patterns in GLOBIGNORE is removed
from the list of matches. The file names ‘‘.’’ and ‘‘..’’ are always
ignored when GLOBIGNORE is set and not null. However, setting GLOBIG-
NORE to a non-null value has the effect of enabling the dotglob shell
option, so all other file names beginning with a ‘‘.’’ will match. To
get the old behavior of ignoring file names beginning with a ‘‘.’’,
make ‘‘.*’’ one of the patterns in GLOBIGNORE. The dotglob option is
disabled when GLOBIGNORE is unset.
Pattern Matching
Any character that appears in a pattern, other than the special pattern
characters described below, matches itself. The NUL character may not
occur in a pattern. A backslash escapes the following character; the
escaping backslash is discarded when matching. The special pattern
characters must be quoted if they are to be matched literally.
The special pattern characters have the following meanings:
* Matches any string, including the null string. When the glob-
star shell option is enabled, and * is used in a pathname expan-
sion context, two adjacent *s used as a single pattern will
match all files and zero or more directories and subdirectories.
If followed by a /, two adjacent *s will match only directories
and subdirectories.
? Matches any single character.
[...] Matches any one of the enclosed characters. A pair of charac-
ters separated by a hyphen denotes a range expression; any char-
acter that sorts between those two characters, inclusive, using
the current locale’s collating sequence and character set, is
matched. If the first character following the [ is a ! or a ^
then any character not enclosed is matched. The sorting order
of characters in range expressions is determined by the current
locale and the value of the LC_COLLATE shell variable, if set.
A - may be matched by including it as the first or last charac-
ter in the set. A ] may be matched by including it as the first
character in the set.
Within [ and ], character classes can be specified using the
syntax [:class:], where class is one of the following classes
defined in the POSIX standard:
alnum alpha ascii blank cntrl digit graph lower print punct
space upper word xdigit
A character class matches any character belonging to that class.
The word character class matches letters, digits, and the char-
acter _.
Within [ and ], an equivalence class can be specified using the
syntax [=c=], which matches all characters with the same colla-
tion weight (as defined by the current locale) as the character
c.
Within [ and ], the syntax [.symbol.] matches the collating sym-
bol symbol.
Several extended pattern matching operators are recognized. In the
following description, a pattern-list is a list of one or more patterns
separated by a |. Composite patterns may be formed using one or more
of the following sub-patterns:
?(pattern-list)
Matches zero or one occurrence of the given patterns
*(pattern-list)
Matches zero or more occurrences of the given patterns
+(pattern-list)
Matches one or more occurrences of the given patterns
@(pattern-list)
Matches one of the given patterns
If the extglob shell option is enabled using the shopt builtin, follow-
ing pattern matching operator is recognized as well:
!(pattern-list)
Matches anything except one of the given patterns
Quote Removal
After the preceding expansions, all unquoted occurrences of the charac-
ters \, ', and " that did not result from one of the above expansions
are removed.
REDIRECTION
Before a command is executed, its input and output may be redirected
using a special notation interpreted by the shell. Redirection may
also be used to open and close files for the current shell execution
environment. The following redirection operators may precede or appear
anywhere within a simple command or may follow a command. Redirections
are processed in the order they appear, from left to right.
Each redirection that may be preceded by a file descriptor number may
instead be preceded by a word of the form {varname}. In this case, for
each redirection operator except >&- and <&-, the shell will allocate a
file descriptor greater than 10 and assign it to varname. If >&- or
<&- is preceded by {varname}, the value of varname defines the file
descriptor to close.
In the following descriptions, if the file descriptor number is omit-
ted, and the first character of the redirection operator is <, the
redirection refers to the standard input (file descriptor 0). If the
first character of the redirection operator is >, the redirection
refers to the standard output (file descriptor 1).
The word following the redirection operator in the following descrip-
tions, unless otherwise noted, is subjected to brace expansion, tilde
expansion, parameter expansion, command substitution, arithmetic expan-
sion, quote removal, pathname expansion, and word splitting. If it
expands to more than one word, bash reports an error.
Note that the order of redirections is significant. For example, the
command
ls > dirlist 2>&1
directs both standard output and standard error to the file dirlist,
while the command
ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard
error was duplicated from the standard output before the standard out-
put was redirected to dirlist.
Bash handles several filenames specially when they are used in redirec-
tions, as described in the following table:
/dev/fd/fd
If fd is a valid integer, file descriptor fd is dupli-
cated.
/dev/stdin
File descriptor 0 is duplicated.
/dev/stdout
File descriptor 1 is duplicated.
/dev/stderr
File descriptor 2 is duplicated.
/dev/tcp/host/port
If host is a valid hostname or Internet address, and port
is an integer port number or service name, bash attempts
to open a TCP connection to the corresponding socket.
/dev/udp/host/port
If host is a valid hostname or Internet address, and port
is an integer port number or service name, bash attempts
to open a UDP connection to the corresponding socket.
A failure to open or create a file causes the redirection to fail.
Redirections using file descriptors greater than 9 should be used with
care, as they may conflict with file descriptors the shell uses inter-
nally.
Redirecting Input
Redirection of input causes the file whose name results from the expan-
sion of word to be opened for reading on file descriptor n, or the
standard input (file descriptor 0) if n is not specified.
The general format for redirecting input is:
[n]word
If the redirection operator is >, and the noclobber option to the set
builtin has been enabled, the redirection will fail if the file whose
name results from the expansion of word exists and is a regular file.
If the redirection operator is >|, or the redirection operator is > and
the noclobber option to the set builtin command is not enabled, the
redirection is attempted even if the file named by word exists.
Appending Redirected Output
Redirection of output in this fashion causes the file whose name
results from the expansion of word to be opened for appending on file
descriptor n, or the standard output (file descriptor 1) if n is not
specified. If the file does not exist it is created.
The general format for appending output is:
[n]>>word
Redirecting Standard Output and Standard Error
This construct allows both the standard output (file descriptor 1) and
the standard error output (file descriptor 2) to be redirected to the
file whose name is the expansion of word.
There are two formats for redirecting standard output and standard
error:
&>word
and
>&word
Of the two forms, the first is preferred. This is semantically equiva-
lent to
>word 2>&1
Appending Standard Output and Standard Error
This construct allows both the standard output (file descriptor 1) and
the standard error output (file descriptor 2) to be appended to the
file whose name is the expansion of word.
The format for appending standard output and standard error is:
&>>word
This is semantically equivalent to
>>word 2>&1
Here Documents
This type of redirection instructs the shell to read input from the
current source until a line containing only delimiter (with no trailing
blanks) is seen. All of the lines read up to that point are then used
as the standard input for a command.
The format of here-documents is:
<<[-]word
here-document
delimiter
No parameter expansion, command substitution, arithmetic expansion, or
pathname expansion is performed on word. If any characters in word are
quoted, the delimiter is the result of quote removal on word, and the
lines in the here-document are not expanded. If word is unquoted, all
lines of the here-document are subjected to parameter expansion, com-
mand substitution, and arithmetic expansion. In the latter case, the
character sequence \ is ignored, and \ must be used to quote
the characters \, $, and `.
If the redirection operator is <<-, then all leading tab characters are
stripped from input lines and the line containing delimiter. This
allows here-documents within shell scripts to be indented in a natural
fashion.
Here Strings
A variant of here documents, the format is:
<<&word
is used similarly to duplicate output file descriptors. If n is not
specified, the standard output (file descriptor 1) is used. If the
digits in word do not specify a file descriptor open for output, a
redirection error occurs. As a special case, if n is omitted, and word
does not expand to one or more digits, the standard output and standard
error are redirected as described previously.
Moving File Descriptors
The redirection operator
[n]<&digit-
moves the file descriptor digit to file descriptor n, or the standard
input (file descriptor 0) if n is not specified. digit is closed after
being duplicated to n.
Similarly, the redirection operator
[n]>&digit-
moves the file descriptor digit to file descriptor n, or the standard
output (file descriptor 1) if n is not specified.
Opening File Descriptors for Reading and Writing
The redirection operator
[n]<>word
causes the file whose name is the expansion of word to be opened for
both reading and writing on file descriptor n, or on file descriptor 0
if n is not specified. If the file does not exist, it is created.
ALIASES
Aliases allow a string to be substituted for a word when it is used as
the first word of a simple command. The shell maintains a list of
aliases that may be set and unset with the alias and unalias builtin
commands (see SHELL BUILTIN COMMANDS below). The first word of each
simple command, if unquoted, is checked to see if it has an alias. If
so, that word is replaced by the text of the alias. The characters /,
$, `, and = and any of the shell metacharacters or quoting characters
listed above may not appear in an alias name. The replacement text may
contain any valid shell input, including shell metacharacters. The
first word of the replacement text is tested for aliases, but a word
that is identical to an alias being expanded is not expanded a second
time. This means that one may alias ls to ls -F, for instance, and
bash does not try to recursively expand the replacement text. If the
last character of the alias value is a blank, then the next command
word following the alias is also checked for alias expansion.
Aliases are created and listed with the alias command, and removed with
the unalias command.
There is no mechanism for using arguments in the replacement text. If
arguments are needed, a shell function should be used (see FUNCTIONS
below).
Aliases are not expanded when the shell is not interactive, unless the
expand_aliases shell option is set using shopt (see the description of
shopt under SHELL BUILTIN COMMANDS below).
The rules concerning the definition and use of aliases are somewhat
confusing. Bash always reads at least one complete line of input
before executing any of the commands on that line. Aliases are
expanded when a command is read, not when it is executed. Therefore,
an alias definition appearing on the same line as another command does
not take effect until the next line of input is read. The commands
following the alias definition on that line are not affected by the new
alias. This behavior is also an issue when functions are executed.
Aliases are expanded when a function definition is read, not when the
function is executed, because a function definition is itself a com-
pound command. As a consequence, aliases defined in a function are not
available until after that function is executed. To be safe, always
put alias definitions on a separate line, and do not use alias in com-
pound commands.
For almost every purpose, aliases are superseded by shell functions.
FUNCTIONS
A shell function, defined as described above under SHELL GRAMMAR,
stores a series of commands for later execution. When the name of a
shell function is used as a simple command name, the list of commands
associated with that function name is executed. Functions are executed
in the context of the current shell; no new process is created to
interpret them (contrast this with the execution of a shell script).
When a function is executed, the arguments to the function become the
positional parameters during its execution. The special parameter # is
updated to reflect the change. Special parameter 0 is unchanged. The
first element of the FUNCNAME variable is set to the name of the func-
tion while the function is executing.
All other aspects of the shell execution environment are identical
between a function and its caller with these exceptions: the DEBUG and
RETURN traps (see the description of the trap builtin under SHELL
BUILTIN COMMANDS below) are not inherited unless the function has been
given the trace attribute (see the description of the declare builtin
below) or the -o functrace shell option has been enabled with the set
builtin (in which case all functions inherit the DEBUG and RETURN
traps), and the ERR trap is not inherited unless the -o errtrace shell
option has been enabled.
Variables local to the function may be declared with the local builtin
command. Ordinarily, variables and their values are shared between the
function and its caller.
If the builtin command return is executed in a function, the function
completes and execution resumes with the next command after the func-
tion call. Any command associated with the RETURN trap is executed
before execution resumes. When a function completes, the values of the
positional parameters and the special parameter # are restored to the
values they had prior to the function’s execution.
Function names and definitions may be listed with the -f option to the
declare or typeset builtin commands. The -F option to declare or type-
set will list the function names only (and optionally the source file
and line number, if the extdebug shell option is enabled). Functions
may be exported so that subshells automatically have them defined with
the -f option to the export builtin. A function definition may be
deleted using the -f option to the unset builtin. Note that shell
functions and variables with the same name may result in multiple iden-
tically-named entries in the environment passed to the shell’s chil-
dren. Care should be taken in cases where this may cause a problem.
Functions may be recursive. No limit is imposed on the number of
recursive calls.
ARITHMETIC EVALUATION
The shell allows arithmetic expressions to be evaluated, under certain
circumstances (see the let and declare builtin commands and Arithmetic
Expansion). Evaluation is done in fixed-width integers with no check
for overflow, though division by 0 is trapped and flagged as an error.
The operators and their precedence, associativity, and values are the
same as in the C language. The following list of operators is grouped
into levels of equal-precedence operators. The levels are listed in
order of decreasing precedence.
id++ id--
variable post-increment and post-decrement
++id --id
variable pre-increment and pre-decrement
- + unary minus and plus
! ~ logical and bitwise negation
** exponentiation
* / % multiplication, division, remainder
+ - addition, subtraction
<< >> left and right bitwise shifts
<= >= < >
comparison
== != equality and inequality
& bitwise AND
^ bitwise exclusive OR
| bitwise OR
&& logical AND
|| logical OR
expr?expr:expr
conditional operator
= *= /= %= += -= <<= >>= &= ^= |=
assignment
expr1 , expr2
comma
Shell variables are allowed as operands; parameter expansion is per-
formed before the expression is evaluated. Within an expression, shell
variables may also be referenced by name without using the parameter
expansion syntax. A shell variable that is null or unset evaluates to
0 when referenced by name without using the parameter expansion syntax.
The value of a variable is evaluated as an arithmetic expression when
it is referenced, or when a variable which has been given the integer
attribute using declare -i is assigned a value. A null value evaluates
to 0. A shell variable need not have its integer attribute turned on
to be used in an expression.
Constants with a leading 0 are interpreted as octal numbers. A leading
0x or 0X denotes hexadecimal. Otherwise, numbers take the form
[base#]n, where base is a decimal number between 2 and 64 representing
the arithmetic base, and n is a number in that base. If base# is omit-
ted, then base 10 is used. The digits greater than 9 are represented
by the lowercase letters, the uppercase letters, @, and _, in that
order. If base is less than or equal to 36, lowercase and uppercase
letters may be used interchangeably to represent numbers between 10 and
35.
Operators are evaluated in order of precedence. Sub-expressions in
parentheses are evaluated first and may override the precedence rules
above.
CONDITIONAL EXPRESSIONS
Conditional expressions are used by the [[ compound command and the
test and [ builtin commands to test file attributes and perform string
and arithmetic comparisons. Expressions are formed from the following
unary or binary primaries. If any file argument to one of the pri-
maries is of the form /dev/fd/n, then file descriptor n is checked. If
the file argument to one of the primaries is one of /dev/stdin,
/dev/stdout, or /dev/stderr, file descriptor 0, 1, or 2, respectively,
is checked.
Unless otherwise specified, primaries that operate on files follow sym-
bolic links and operate on the target of the link, rather than the link
itself.
When used with [[, The < and > operators sort lexicographically using
the current locale.
-a file
True if file exists.
-b file
True if file exists and is a block special file.
-c file
True if file exists and is a character special file.
-d file
True if file exists and is a directory.
-e file
True if file exists.
-f file
True if file exists and is a regular file.
-g file
True if file exists and is set-group-id.
-h file
True if file exists and is a symbolic link.
-k file
True if file exists and its ‘‘sticky’’ bit is set.
-p file
True if file exists and is a named pipe (FIFO).
-r file
True if file exists and is readable.
-s file
True if file exists and has a size greater than zero.
-t fd True if file descriptor fd is open and refers to a terminal.
-u file
True if file exists and its set-user-id bit is set.
-w file
True if file exists and is writable.
-x file
True if file exists and is executable.
-O file
True if file exists and is owned by the effective user id.
-G file
True if file exists and is owned by the effective group id.
-L file
True if file exists and is a symbolic link.
-S file
True if file exists and is a socket.
-N file
True if file exists and has been modified since it was last
read.
file1 -nt file2
True if file1 is newer (according to modification date) than
file2, or if file1 exists and file2 does not.
file1 -ot file2
True if file1 is older than file2, or if file2 exists and file1
does not.
file1 -ef file2
True if file1 and file2 refer to the same device and inode num-
bers.
-o optname
True if shell option optname is enabled. See the list of
options under the description of the -o option to the set
builtin below.
-z string
True if the length of string is zero.
string
-n string
True if the length of string is non-zero.
string1 == string2
string1 = string2
True if the strings are equal. = should be used with the test
command for POSIX conformance.
string1 != string2
True if the strings are not equal.
string1 < string2
True if string1 sorts before string2 lexicographically.
string1 > string2
True if string1 sorts after string2 lexicographically.
arg1 OP arg2
OP is one of -eq, -ne, -lt, -le, -gt, or -ge. These arithmetic
binary operators return true if arg1 is equal to, not equal to,
less than, less than or equal to, greater than, or greater than
or equal to arg2, respectively. Arg1 and arg2 may be positive
or negative integers.
SIMPLE COMMAND EXPANSION
When a simple command is executed, the shell performs the following
expansions, assignments, and redirections, from left to right.
1. The words that the parser has marked as variable assignments
(those preceding the command name) and redirections are saved
for later processing.
2. The words that are not variable assignments or redirections are
expanded. If any words remain after expansion, the first word
is taken to be the name of the command and the remaining words
are the arguments.
3. Redirections are performed as described above under REDIRECTION.
4. The text after the = in each variable assignment undergoes tilde
expansion, parameter expansion, command substitution, arithmetic
expansion, and quote removal before being assigned to the vari-
able.
If no command name results, the variable assignments affect the current
shell environment. Otherwise, the variables are added to the environ-
ment of the executed command and do not affect the current shell envi-
ronment. If any of the assignments attempts to assign a value to a
readonly variable, an error occurs, and the command exits with a non-
zero status.
If no command name results, redirections are performed, but do not
affect the current shell environment. A redirection error causes the
command to exit with a non-zero status.
If there is a command name left after expansion, execution proceeds as
described below. Otherwise, the command exits. If one of the expan-
sions contained a command substitution, the exit status of the command
is the exit status of the last command substitution performed. If
there were no command substitutions, the command exits with a status of
zero.
COMMAND EXECUTION
After a command has been split into words, if it results in a simple
command and an optional list of arguments, the following actions are
taken.
If the command name contains no slashes, the shell attempts to locate
it. If there exists a shell function by that name, that function is
invoked as described above in FUNCTIONS. If the name does not match a
function, the shell searches for it in the list of shell builtins. If
a match is found, that builtin is invoked.
If the name is neither a shell function nor a builtin, and contains no
slashes, bash searches each element of the PATH for a directory con-
taining an executable file by that name. Bash uses a hash table to
remember the full pathnames of executable files (see hash under SHELL
BUILTIN COMMANDS below). A full search of the directories in PATH is
performed only if the command is not found in the hash table. If the
search is unsuccessful, the shell searches for a defined shell function
named command_not_found_handle. If that function exists, it is invoked
with the original command and the original command’s arguments as its
arguments, and the function’s exit status becomes the exit status of
the shell. If that function is not defined, the shell prints an error
message and returns an exit status of 127.
If the search is successful, or if the command name contains one or
more slashes, the shell executes the named program in a separate execu-
tion environment. Argument 0 is set to the name given, and the remain-
ing arguments to the command are set to the arguments given, if any.
If this execution fails because the file is not in executable format,
and the file is not a directory, it is assumed to be a shell script, a
file containing shell commands. A subshell is spawned to execute it.
This subshell reinitializes itself, so that the effect is as if a new
shell had been invoked to handle the script, with the exception that
the locations of commands remembered by the parent (see hash below
under SHELL BUILTIN COMMANDS) are retained by the child.
If the program is a file beginning with #!, the remainder of the first
line specifies an interpreter for the program. The shell executes the
specified interpreter on operating systems that do not handle this exe-
cutable format themselves. The arguments to the interpreter consist of
a single optional argument following the interpreter name on the first
line of the program, followed by the name of the program, followed by
the command arguments, if any.
COMMAND EXECUTION ENVIRONMENT
The shell has an execution environment, which consists of the follow-
ing:
· open files inherited by the shell at invocation, as modified by
redirections supplied to the exec builtin
· the current working directory as set by cd, pushd, or popd, or
inherited by the shell at invocation
· the file creation mode mask as set by umask or inherited from
the shell’s parent
· current traps set by trap
· shell parameters that are set by variable assignment or with set
or inherited from the shell’s parent in the environment
· shell functions defined during execution or inherited from the
shell’s parent in the environment
· options enabled at invocation (either by default or with com-
mand-line arguments) or by set
· options enabled by shopt
· shell aliases defined with alias
· various process IDs, including those of background jobs, the
value of $$, and the value of PPID
When a simple command other than a builtin or shell function is to be
executed, it is invoked in a separate execution environment that con-
sists of the following. Unless otherwise noted, the values are inher-
ited from the shell.
· the shell’s open files, plus any modifications and additions
specified by redirections to the command
· the current working directory
· the file creation mode mask
· shell variables and functions marked for export, along with
variables exported for the command, passed in the environment
· traps caught by the shell are reset to the values inherited from
the shell’s parent, and traps ignored by the shell are ignored
A command invoked in this separate environment cannot affect the
shell’s execution environment.
Command substitution, commands grouped with parentheses, and asyn-
chronous commands are invoked in a subshell environment that is a
duplicate of the shell environment, except that traps caught by the
shell are reset to the values that the shell inherited from its parent
at invocation. Builtin commands that are invoked as part of a pipeline
are also executed in a subshell environment. Changes made to the sub-
shell environment cannot affect the shell’s execution environment.
Subshells spawned to execute command substitutions inherit the value of
the -e option from the parent shell. When not in posix mode, Bash
clears the -e option in such subshells.
If a command is followed by a & and job control is not active, the
default standard input for the command is the empty file /dev/null.
Otherwise, the invoked command inherits the file descriptors of the
calling shell as modified by redirections.
ENVIRONMENT
When a program is invoked it is given an array of strings called the
environment. This is a list of name-value pairs, of the form
name=value.
The shell provides several ways to manipulate the environment. On
invocation, the shell scans its own environment and creates a parameter
for each name found, automatically marking it for export to child pro-
cesses. Executed commands inherit the environment. The export and
declare -x commands allow parameters and functions to be added to and
deleted from the environment. If the value of a parameter in the envi-
ronment is modified, the new value becomes part of the environment,
replacing the old. The environment inherited by any executed command
consists of the shell’s initial environment, whose values may be modi-
fied in the shell, less any pairs removed by the unset command, plus
any additions via the export and declare -x commands.
The environment for any simple command or function may be augmented
temporarily by prefixing it with parameter assignments, as described
above in PARAMETERS. These assignment statements affect only the envi-
ronment seen by that command.
If the -k option is set (see the set builtin command below), then all
parameter assignments are placed in the environment for a command, not
just those that precede the command name.
When bash invokes an external command, the variable _ is set to the
full file name of the command and passed to that command in its envi-
ronment.
EXIT STATUS
The exit status of an executed command is the value returned by the
waitpid system call or equivalent function. Exit statuses fall between
0 and 255, though, as explained below, the shell may use values above
125 specially. Exit statuses from shell builtins and compound commands
are also limited to this range. Under certain circumstances, the shell
will use special values to indicate specific failure modes.
For the shell’s purposes, a command which exits with a zero exit status
has succeeded. An exit status of zero indicates success. A non-zero
exit status indicates failure. When a command terminates on a fatal
signal N, bash uses the value of 128+N as the exit status.
If a command is not found, the child process created to execute it
returns a status of 127. If a command is found but is not executable,
the return status is 126.
If a command fails because of an error during expansion or redirection,
the exit status is greater than zero.
Shell builtin commands return a status of 0 (true) if successful, and
non-zero (false) if an error occurs while they execute. All builtins
return an exit status of 2 to indicate incorrect usage.
Bash itself returns the exit status of the last command executed,
unless a syntax error occurs, in which case it exits with a non-zero
value. See also the exit builtin command below.
SIGNALS
When bash is interactive, in the absence of any traps, it ignores
SIGTERM (so that kill 0 does not kill an interactive shell), and SIGINT
is caught and handled (so that the wait builtin is interruptible). In
all cases, bash ignores SIGQUIT. If job control is in effect, bash
ignores SIGTTIN, SIGTTOU, and SIGTSTP.
Non-builtin commands run by bash have signal handlers set to the values
inherited by the shell from its parent. When job control is not in
effect, asynchronous commands ignore SIGINT and SIGQUIT in addition to
these inherited handlers. Commands run as a result of command substi-
tution ignore the keyboard-generated job control signals SIGTTIN, SIGT-
TOU, and SIGTSTP.
The shell exits by default upon receipt of a SIGHUP. Before exiting,
an interactive shell resends the SIGHUP to all jobs, running or
stopped. Stopped jobs are sent SIGCONT to ensure that they receive the
SIGHUP. To prevent the shell from sending the signal to a particular
job, it should be removed from the jobs table with the disown builtin
(see SHELL BUILTIN COMMANDS below) or marked to not receive SIGHUP
using disown -h.
If the huponexit shell option has been set with shopt, bash sends a
SIGHUP to all jobs when an interactive login shell exits.
If bash is waiting for a command to complete and receives a signal for
which a trap has been set, the trap will not be executed until the com-
mand completes. When bash is waiting for an asynchronous command via
the wait builtin, the reception of a signal for which a trap has been
set will cause the wait builtin to return immediately with an exit sta-
tus greater than 128, immediately after which the trap is executed.
JOB CONTROL
Job control refers to the ability to selectively stop (suspend) the
execution of processes and continue (resume) their execution at a later
point. A user typically employs this facility via an interactive
interface supplied jointly by the operating system kernel’s terminal
driver and bash.
The shell associates a job with each pipeline. It keeps a table of
currently executing jobs, which may be listed with the jobs command.
When bash starts a job asynchronously (in the background), it prints a
line that looks like:
[1] 25647
indicating that this job is job number 1 and that the process ID of the
last process in the pipeline associated with this job is 25647. All of
the processes in a single pipeline are members of the same job. Bash
uses the job abstraction as the basis for job control.
To facilitate the implementation of the user interface to job control,
the operating system maintains the notion of a current terminal process
group ID. Members of this process group (processes whose process group
ID is equal to the current terminal process group ID) receive keyboard-
generated signals such as SIGINT. These processes are said to be in
the foreground. Background processes are those whose process group ID
differs from the terminal’s; such processes are immune to keyboard-gen-
erated signals. Only foreground processes are allowed to read from or,
if the user so specifies with stty tostop, write to the terminal.
Background processes which attempt to read from (write to when stty
tostop is in effect) the terminal are sent a SIGTTIN (SIGTTOU) signal
by the kernel’s terminal driver, which, unless caught, suspends the
process.
If the operating system on which bash is running supports job control,
bash contains facilities to use it. Typing the suspend character (typ-
ically ^Z, Control-Z) while a process is running causes that process to
be stopped and returns control to bash. Typing the delayed suspend
character (typically ^Y, Control-Y) causes the process to be stopped
when it attempts to read input from the terminal, and control to be
returned to bash. The user may then manipulate the state of this job,
using the bg command to continue it in the background, the fg command
to continue it in the foreground, or the kill command to kill it. A ^Z
takes effect immediately, and has the additional side effect of causing
pending output and typeahead to be discarded.
There are a number of ways to refer to a job in the shell. The charac-
ter % introduces a job specification (jobspec). Job number n may be
referred to as %n. A job may also be referred to using a prefix of the
name used to start it, or using a substring that appears in its command
line. For example, %ce refers to a stopped ce job. If a prefix
matches more than one job, bash reports an error. Using %?ce, on the
other hand, refers to any job containing the string ce in its command
line. If the substring matches more than one job, bash reports an
error. The symbols %% and %+ refer to the shell’s notion of the cur-
rent job, which is the last job stopped while it was in the foreground
or started in the background. The previous job may be referenced using
%-. If there is only a single job, %+ and %- can both be used to refer
to that job. In output pertaining to jobs (e.g., the output of the
jobs command), the current job is always flagged with a +, and the pre-
vious job with a -. A single % (with no accompanying job specifica-
tion) also refers to the current job.
Simply naming a job can be used to bring it into the foreground: %1 is
a synonym for ‘‘fg %1’’, bringing job 1 from the background into the
foreground. Similarly, ‘‘%1 &’’ resumes job 1 in the background,
equivalent to ‘‘bg %1’’.
The shell learns immediately whenever a job changes state. Normally,
bash waits until it is about to print a prompt before reporting changes
in a job’s status so as to not interrupt any other output. If the -b
option to the set builtin command is enabled, bash reports such changes
immediately. Any trap on SIGCHLD is executed for each child that
exits.
If an attempt to exit bash is made while jobs are stopped (or, if the
checkjobs shell option has been enabled using the shopt builtin, run-
ning), the shell prints a warning message, and, if the checkjobs option
is enabled, lists the jobs and their statuses. The jobs command may
then be used to inspect their status. If a second attempt to exit is
made without an intervening command, the shell does not print another
warning, and any stopped jobs are terminated.
PROMPTING
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 customized 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")
\D{format}
the format is passed to strftime(3) and the result is
inserted into the prompt string; an empty format results
in a locale-specific time representation. The braces are
required
\e an ASCII escape character (033)
\h the hostname up to the first ‘.’
\H the hostname
\j the number of jobs currently managed by the shell
\l the basename of the shell’s terminal device name
\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
\A the current time in 24-hour HH:MM format
\u the username of the current user
\v the version of bash (e.g., 2.00)
\V the release of bash, version + patch level (e.g., 2.00.0)
\w the current working directory, with $HOME abbreviated
with a tilde (uses the value of the PROMPT_DIRTRIM vari-
able)
\W the basename of the current working directory, with $HOME
abbreviated with a tilde
\! 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 control sequence into the
prompt
\] end a sequence of non-printing characters
The command number and the history number are usually different: the
history number of a command is its position in the history list, which
may include commands restored from the history file (see HISTORY
below), while the command number is the position in the sequence of
commands executed during the current shell session. After the string
is decoded, it is expanded via parameter expansion, command substitu-
tion, arithmetic expansion, and quote removal, subject to the value of
the promptvars shell option (see the description of the shopt command
under SHELL BUILTIN COMMANDS below).
READLINE
This is the library that handles reading input when using an interac-
tive shell, unless the --noediting option is given at shell invocation.
Line editing is also used when using the -e option to the read builtin.
By default, the line editing commands are similar to those of emacs. A
vi-style line editing interface is also available. Line editing can be
enabled at any time using the -o emacs or -o vi options to the set
builtin (see SHELL BUILTIN COMMANDS below). To turn off line editing
after the shell is running, use the +o emacs or +o vi options to the
set builtin.
Readline Notation
In this section, the emacs-style notation is used to denote keystrokes.
Control keys are denoted by C-key, e.g., C-n means Control-N. Simi-
larly, meta keys are denoted by M-key, so M-x means Meta-X. (On key-
boards without a meta key, M-x means ESC x, i.e., press the Escape key
then the x key. This makes ESC the meta prefix. The combination M-C-x
means ESC-Control-x, or press the Escape key then hold the Control key
while pressing the x key.)
Readline commands may be given numeric arguments, which normally act as
a repeat count. Sometimes, however, it is the sign of the argument
that is significant. Passing a negative argument to a command that
acts in the forward direction (e.g., kill-line) causes that command to
act in a backward direction. Commands whose behavior with arguments
deviates from this are noted below.
When a command is described as killing text, the text deleted is saved
for possible future retrieval (yanking). The killed text is saved in a
kill ring. Consecutive kills cause the text to be accumulated into one
unit, which can be yanked all at once. Commands which do not kill text
separate the chunks of text on the kill ring.
Readline Initialization
Readline is customized by putting commands in an initialization file
(the inputrc file). The name of this file is taken from the value of
the INPUTRC variable. If that variable is unset, the default is
~/.inputrc. When a program which uses the readline library starts up,
the initialization file is read, and the key bindings and variables are
set. There are only a few basic constructs allowed in the readline
initialization file. Blank lines are ignored. Lines beginning with a
# are comments. Lines beginning with a $ indicate conditional con-
structs. Other lines denote key bindings and variable settings.
The default key-bindings may be changed with an inputrc file. Other
programs that use this library may add their own commands and bindings.
For example, placing
M-Control-u: universal-argument
or
C-Meta-u: universal-argument
into the inputrc would make M-C-u execute the readline command univer-
sal-argument.
The following symbolic character names are recognized: RUBOUT, DEL,
ESC, LFD, NEWLINE, RET, RETURN, SPC, SPACE, and TAB.
In addition to command names, readline allows keys to be bound to a
string that is inserted when the key is pressed (a macro).
Readline Key Bindings
The syntax for controlling key bindings in the inputrc file is simple.
All that is required is the name of the command or the text of a macro
and a key sequence to which it should be bound. The name may be speci-
fied in one of two ways: as a symbolic key name, possibly with Meta- or
Control- prefixes, or as a key sequence.
When using the form keyname:function-name or macro, keyname is the name
of a key spelled out in English. For example:
Control-u: universal-argument
Meta-Rubout: backward-kill-word
Control-o: "> output"
In the above example, C-u is bound to the function universal-argument,
M-DEL is bound to the function backward-kill-word, and C-o is bound to
run the macro expressed on the right hand side (that is, to insert the
text ‘‘> output’’ into the line).
In the second form, "keyseq":function-name or macro, keyseq differs
from keyname above in that strings denoting an entire key sequence may
be specified by placing the sequence within double quotes. Some GNU
Emacs style key escapes can be used, as in the following example, but
the symbolic character names are not recognized.
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file
"\e[11~": "Function Key 1"
In this example, C-u is again bound to the function universal-argument.
C-x C-r is bound to the function re-read-init-file, and ESC [ 1 1 ~ is
bound to insert the text ‘‘Function Key 1’’.
The full set of GNU Emacs style escape sequences is
\C- control prefix
\M- meta prefix
\e an escape character
\\ backslash
\" literal "
\' literal '
In addition to the GNU Emacs style escape sequences, a second set of
backslash escapes is available:
\a alert (bell)
\b backspace
\d delete
\f form feed
\n newline
\r carriage return
\t horizontal tab
\v vertical tab
\nnn the eight-bit character whose value is the octal value
nnn (one to three digits)
\xHH the eight-bit character whose value is the hexadecimal
value HH (one or two hex digits)
When entering the text of a macro, single or double quotes must be used
to indicate a macro definition. Unquoted text is assumed to be a func-
tion name. In the macro body, the backslash escapes described above
are expanded. Backslash will quote any other character in the macro
text, including " and '.
Bash allows the current readline key bindings to be displayed or modi-
fied with the bind builtin command. The editing mode may be switched
during interactive use by using the -o option to the set builtin com-
mand (see SHELL BUILTIN COMMANDS below).
Readline Variables
Readline has variables that can be used to further customize its behav-
ior. A variable may be set in the inputrc file with a statement of the
form
set variable-name value
Except where noted, readline variables can take the values On or Off
(without regard to case). Unrecognized variable names are ignored.
When a variable value is read, empty or null values, "on" (case-insen-
sitive), and "1" are equivalent to On. All other values are equivalent
to Off. The variables and their default values are:
bell-style (audible)
Controls what happens when readline wants to ring the terminal
bell. If set to none, readline never rings the bell. If set to
visible, readline uses a visible bell if one is available. If
set to audible, readline attempts to ring the terminal’s bell.
bind-tty-special-chars (On)
If set to On, readline attempts to bind the control characters
treated specially by the kernel’s terminal driver to their read-
line equivalents.
comment-begin (‘‘#’’)
The string that is inserted when the readline insert-comment
command is executed. This command is bound to M-# in emacs mode
and to # in vi command mode.
completion-ignore-case (Off)
If set to On, readline performs filename matching and completion
in a case-insensitive fashion.
completion-prefix-display-length (0)
The length in characters of the common prefix of a list of pos-
sible completions that is displayed without modification. When
set to a value greater than zero, common prefixes longer than
this value are replaced with an ellipsis when displaying possi-
ble completions.
completion-query-items (100)
This determines when the user is queried about viewing the num-
ber of possible completions generated by the possible-comple-
tions command. It may be set to any integer value greater than
or equal to zero. If the number of possible completions is
greater than or equal to the value of this variable, the user is
asked whether or not he wishes to view them; otherwise they are
simply listed on the terminal.
convert-meta (On)
If set to On, readline will convert characters with the eighth
bit set to an ASCII key sequence by stripping the eighth bit and
prefixing an escape character (in effect, using escape as the
meta prefix).
disable-completion (Off)
If set to On, readline will inhibit word completion. Completion
characters will be inserted into the line as if they had been
mapped to self-insert.
editing-mode (emacs)
Controls whether readline begins with a set of key bindings sim-
ilar to emacs or vi. editing-mode can be set to either emacs or
vi.
echo-control-characters (On)
When set to On, on operating systems that indicate they support
it, readline echoes a character corresponding to a signal gener-
ated from the keyboard.
enable-keypad (Off)
When set to On, readline will try to enable the application key-
pad when it is called. Some systems need this to enable the
arrow keys.
enable-meta-key (On)
When set to On, readline will try to enable any meta modifier
key the terminal claims to support when it is called. On many
terminals, the meta key is used to send eight-bit characters.
expand-tilde (Off)
If set to on, tilde expansion is performed when readline
attempts word completion.
history-preserve-point (Off)
If set to on, the history code attempts to place point at the
same location on each history line retrieved with previous-his-
tory or next-history.
history-size (0)
Set the maximum number of history entries saved in the history
list. If set to zero, the number of entries in the history list
is not limited.
horizontal-scroll-mode (Off)
When set to On, makes readline use a single line for display,
scrolling the input horizontally on a single screen line when it
becomes longer than the screen width rather than wrapping to a
new line.
input-meta (Off)
If set to On, readline will enable eight-bit input (that is, it
will not strip the high bit from the characters it reads),
regardless of what the terminal claims it can support. The name
meta-flag is a synonym for this variable.
isearch-terminators (‘‘C-[C-J’’)
The string of characters that should terminate an incremental
search without subsequently executing the character as a com-
mand. If this variable has not been given a value, the charac-
ters ESC and C-J will terminate an incremental search.
keymap (emacs)
Set the current readline keymap. The set of valid keymap names
is emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-com-
mand, and vi-insert. vi is equivalent to vi-command; emacs is
equivalent to emacs-standard. The default value is emacs; the
value of editing-mode also affects the default keymap.
mark-directories (On)
If set to On, completed directory names have a slash appended.
mark-modified-lines (Off)
If set to On, history lines that have been modified are dis-
played with a preceding asterisk (*).
mark-symlinked-directories (Off)
If set to On, completed names which are symbolic links to direc-
tories have a slash appended (subject to the value of
mark-directories).
match-hidden-files (On)
This variable, when set to On, causes readline to match files
whose names begin with a ‘.’ (hidden files) when performing
filename completion, unless the leading ‘.’ is supplied by the
user in the filename to be completed.
output-meta (Off)
If set to On, readline will display characters with the eighth
bit set directly rather than as a meta-prefixed escape sequence.
page-completions (On)
If set to On, readline uses an internal more-like pager to dis-
play a screenful of possible completions at a time.
print-completions-horizontally (Off)
If set to On, readline will display completions with matches
sorted horizontally in alphabetical order, rather than down the
screen.
revert-all-at-newline (Off)
If set to on, readline will undo all changes to history lines
before returning when accept-line is executed. By default, his-
tory lines may be modified and retain individual undo lists
across calls to readline.
show-all-if-ambiguous (Off)
This alters the default behavior of the completion functions.
If set to on, words which have more than one possible completion
cause the matches to be listed immediately instead of ringing
the bell.
show-all-if-unmodified (Off)
This alters the default behavior of the completion functions in
a fashion similar to show-all-if-ambiguous. If set to on, words
which have more than one possible completion without any possi-
ble partial completion (the possible completions don’t share a
common prefix) cause the matches to be listed immediately
instead of ringing the bell.
skip-completed-text (Off)
If set to On, this alters the default completion behavior when
inserting a single match into the line. It’s only active when
performing completion in the middle of a word. If enabled,
readline does not insert characters from the completion that
match characters after point in the word being completed, so
portions of the word following the cursor are not duplicated.
visible-stats (Off)
If set to On, a character denoting a file’s type as reported by
stat(2) is appended to the filename when listing possible com-
pletions.
Readline Conditional Constructs
Readline implements a facility similar in spirit to the conditional
compilation features of the C preprocessor which allows key bindings
and variable settings to be performed as the result of tests. There
are four parser directives used.
$if The $if construct allows bindings to be made based on the edit-
ing mode, the terminal being used, or the application using
readline. The text of the test extends to the end of the line;
no characters are required to isolate it.
mode The mode= form of the $if directive is used to test
whether readline is in emacs or vi mode. This may be
used in conjunction with the set keymap command, for
instance, to set bindings in the emacs-standard and
emacs-ctlx keymaps only if readline is starting out in
emacs mode.
term The term= form may be used to include terminal-specific
key bindings, perhaps to bind the key sequences output by
the terminal’s function keys. The word on the right side
of the = is tested against the both full name of the ter-
minal and the portion of the terminal name before the
first -. This allows sun to match both sun and sun-cmd,
for instance.
application
The application construct is used to include application-
specific settings. Each program using the readline
library sets the application name, and an initialization
file can test for a particular value. This could be used
to bind key sequences to functions useful for a specific
program. For instance, the following command adds a key
sequence that quotes the current or previous word in
Bash:
$if Bash
# Quote the current or previous word
"\C-xq": "\eb\"\ef\""
$endif
$endif This command, as seen in the previous example, terminates an $if
command.
$else Commands in this branch of the $if directive are executed if the
test fails.
$include
This directive takes a single filename as an argument and reads
commands and bindings from that file. For example, the
following directive would read /etc/inputrc:
$include /etc/inputrc
Searching
Readline provides commands for searching through the command history
(see HISTORY below) for lines containing a specified string. There are
two search modes: incremental and non-incremental.
Incremental searches begin before the user has finished typing the
search string. As each character of the search string is typed, read-
line displays the next entry from the history matching the string typed
so far. An incremental search requires only as many characters as
needed to find the desired history entry. The characters present in
the value of the isearch-terminators variable are used to terminate an
incremental search. If that variable has not been assigned a value the
Escape and Control-J characters will terminate an incremental search.
Control-G will abort an incremental search and restore the original
line. When the search is terminated, the history entry containing the
search string becomes the current line.
To find other matching entries in the history list, type Control-S or
Control-R as appropriate. This will search backward or forward in the
history for the next entry matching the search string typed so far.
Any other key sequence bound to a readline command will terminate the
search and execute that command. For instance, a newline will termi-
nate the search and accept the line, thereby executing the command from
the history list.
Readline remembers the last incremental search string. If two Control-
Rs are typed without any intervening characters defining a new search
string, any remembered search string is used.
Non-incremental searches read the entire search string before starting
to search for matching history lines. The search string may be typed
by the user or be part of the contents of the current line.
Readline Command Names
The following is a list of the names of the commands and the default
key sequences to which they are bound. Command names without an accom-
panying key sequence are unbound by default. In the following descrip-
tions, point refers to the current cursor position, and mark refers to
a cursor position saved by the set-mark command. The text between the
point and mark is referred to as the region.
Commands for Moving
beginning-of-line (C-a)
Move to the start of the current line.
end-of-line (C-e)
Move to the end of the line.
forward-char (C-f)
Move forward a character.
backward-char (C-b)
Move back a character.
forward-word (M-f)
Move forward to the end of the next word. Words are composed of
alphanumeric characters (letters and digits).
backward-word (M-b)
Move back to the start of the current or previous word. Words
are composed of alphanumeric characters (letters and digits).
shell-forward-word
Move forward to the end of the next word. Words are delimited
by non-quoted shell metacharacters.
shell-backward-word
Move back to the start of the current or previous word. Words
are delimited by non-quoted shell metacharacters.
clear-screen (C-l)
Clear the screen leaving the current line at the top of the
screen. With an argument, refresh the current line without
clearing the screen.
redraw-current-line
Refresh the current line.
Commands for Manipulating the History
accept-line (Newline, Return)
Accept the line regardless of where the cursor is. If this line
is non-empty, add it to the history list according to the state
of the HISTCONTROL variable. If the line is a modified history
line, then restore the history line to its original state.
previous-history (C-p)
Fetch the previous command from the history list, moving back in
the list.
next-history (C-n)
Fetch the next command from the history list, moving forward in
the list.
beginning-of-history (M-<)
Move to the first line in the history.
end-of-history (M->)
Move to the end of the input history, i.e., the line currently
being entered.
reverse-search-history (C-r)
Search backward starting at the current line and moving ‘up’
through the history as necessary. This is an incremental
search.
forward-search-history (C-s)
Search forward starting at the current line and moving ‘down’
through the history as necessary. This is an incremental
search.
non-incremental-reverse-search-history (M-p)
Search backward through the history starting at the current line
using a non-incremental search for a string supplied by the
user.
non-incremental-forward-search-history (M-n)
Search forward through the history using a non-incremental
search for a string supplied by the user.
history-search-forward
Search forward through the history for the string of characters
between the start of the current line and the point. This is a
non-incremental search.
history-search-backward
Search backward through the history for the string of characters
between the start of the current line and the point. This is a
non-incremental search.
yank-nth-arg (M-C-y)
Insert the first argument to the previous command (usually the
second word on the previous line) at point. With an argument n,
insert the nth word from the previous command (the words in the
previous command begin with word 0). A negative argument
inserts the nth word from the end of the previous command. Once
the argument n is computed, the argument is extracted as if the
"!n" history expansion had been specified.
yank-last-arg (M-., M-_)
Insert the last argument to the previous command (the last word
of the previous history entry). With an argument, behave
exactly like yank-nth-arg. Successive calls to yank-last-arg
move back through the history list, inserting the last argument
of each line in turn. The history expansion facilities are used
to extract the last argument, as if the "!$" history expansion
had been specified.
shell-expand-line (M-C-e)
Expand the line as the shell does. This performs alias and his-
tory expansion as well as all of the shell word expansions. See
HISTORY EXPANSION below for a description of history expansion.
history-expand-line (M-^)
Perform history expansion on the current line. See HISTORY
EXPANSION below for a description of history expansion.
magic-space
Perform history expansion on the current line and insert a
space. See HISTORY EXPANSION below for a description of history
expansion.
alias-expand-line
Perform alias expansion on the current line. See ALIASES above
for a description of alias expansion.
history-and-alias-expand-line
Perform history and alias expansion on the current line.
insert-last-argument (M-., M-_)
A synonym for yank-last-arg.
operate-and-get-next (C-o)
Accept the current line for execution and fetch the next line
relative to the current line from the history for editing. Any
argument is ignored.
edit-and-execute-command (C-xC-e)
Invoke an editor on the current command line, and execute the
result as shell commands. Bash attempts to invoke $VISUAL,
$EDITOR, and emacs as the editor, in that order.
Commands for Changing Text
delete-char (C-d)
Delete the character at point. If point is at the beginning of
the line, there are no characters in the line, and the last
character typed was not bound to delete-char, then return EOF.
backward-delete-char (Rubout)
Delete the character behind the cursor. When given a numeric
argument, save the deleted text on the kill ring.
forward-backward-delete-char
Delete the character under the cursor, unless the cursor is at
the end of the line, in which case the character behind the cur-
sor is deleted.
quoted-insert (C-q, C-v)
Add the next character typed to the line verbatim. This is how
to insert characters like C-q, for example.
tab-insert (C-v TAB)
Insert a tab character.
self-insert (a, b, A, 1, !, ...)
Insert the character typed.
transpose-chars (C-t)
Drag the character before point forward over the character at
point, moving point forward as well. If point is at the end of
the line, then this transposes the two characters before point.
Negative arguments have no effect.
transpose-words (M-t)
Drag the word before point past the word after point, moving
point over that word as well. If point is at the end of the
line, this transposes the last two words on the line.
upcase-word (M-u)
Uppercase the current (or following) word. With a negative
argument, uppercase the previous word, but do not move point.
downcase-word (M-l)
Lowercase the current (or following) word. With a negative
argument, lowercase the previous word, but do not move point.
capitalize-word (M-c)
Capitalize the current (or following) word. With a negative
argument, capitalize the previous word, but do not move point.
overwrite-mode
Toggle overwrite mode. With an explicit positive numeric argu-
ment, switches to overwrite mode. With an explicit non-positive
numeric argument, switches to insert mode. This command affects
only emacs mode; vi mode does overwrite differently. Each call
to readline() starts in insert mode. In overwrite mode, charac-
ters bound to self-insert replace the text at point rather than
pushing the text to the right. Characters bound to back-
ward-delete-char replace the character before point with a
space. By default, this command is unbound.
Killing and Yanking
kill-line (C-k)
Kill the text from point to the end of the line.
backward-kill-line (C-x Rubout)
Kill backward to the beginning of the line.
unix-line-discard (C-u)
Kill backward from point to the beginning of the line. The
killed text is saved on the kill-ring.
kill-whole-line
Kill all characters on the current line, no matter where point
is.
kill-word (M-d)
Kill from point to the end of the current word, or if between
words, to the end of the next word. Word boundaries are the
same as those used by forward-word.
backward-kill-word (M-Rubout)
Kill the word behind point. Word boundaries are the same as
those used by backward-word.
shell-kill-word (M-d)
Kill from point to the end of the current word, or if between
words, to the end of the next word. Word boundaries are the
same as those used by shell-forward-word.
shell-backward-kill-word (M-Rubout)
Kill the word behind point. Word boundaries are the same as
those used by shell-backward-word.
unix-word-rubout (C-w)
Kill the word behind point, using white space as a word bound-
ary. The killed text is saved on the kill-ring.
unix-filename-rubout
Kill the word behind point, using white space and the slash
character as the word boundaries. The killed text is saved on
the kill-ring.
delete-horizontal-space (M-\)
Delete all spaces and tabs around point.
kill-region
Kill the text in the current region.
copy-region-as-kill
Copy the text in the region to the kill buffer.
copy-backward-word
Copy the word before point to the kill buffer. The word bound-
aries are the same as backward-word.
copy-forward-word
Copy the word following point to the kill buffer. The word
boundaries are the same as forward-word.
yank (C-y)
Yank the top of the kill ring into the buffer at point.
yank-pop (M-y)
Rotate the kill ring, and yank the new top. Only works follow-
ing yank or yank-pop.
Numeric Arguments
digit-argument (M-0, M-1, ..., M--)
Add this digit to the argument already accumulating, or start a
new argument. M-- starts a negative argument.
universal-argument
This is another way to specify an argument. If this command is
followed by one or more digits, optionally with a leading minus
sign, those digits define the argument. If the command is fol-
lowed by digits, executing universal-argument again ends the
numeric argument, but is otherwise ignored. As a special case,
if this command is immediately followed by a character that is
neither a digit or minus sign, the argument count for the next
command is multiplied by four. The argument count is initially
one, so executing this function the first time makes the argu-
ment count four, a second time makes the argument count sixteen,
and so on.
Completing
complete (TAB)
Attempt to perform completion on the text before point. Bash
attempts completion treating the text as a variable (if the text
begins with $), username (if the text begins with ~), hostname
(if the text begins with @), or command (including aliases and
functions) in turn. If none of these produces a match, filename
completion is attempted.
possible-completions (M-?)
List the possible completions of the text before point.
insert-completions (M-*)
Insert all completions of the text before point that would have
been generated by possible-completions.
menu-complete
Similar to complete, but replaces the word to be completed with
a single match from the list of possible completions. Repeated
execution of menu-complete steps through the list of possible
completions, inserting each match in turn. At the end of the
list of completions, the bell is rung (subject to the setting of
bell-style) and the original text is restored. An argument of n
moves n positions forward in the list of matches; a negative
argument may be used to move backward through the list. This
command is intended to be bound to TAB, but is unbound by
defaultc
menu-complete-krd
Identical to menu-complete, but moves backward through the list
of possible completions, as if menu-complete had been given a
negative argument. This command is unbound by default.
delete-char-or-list
Deletes the character under the cursor if not at the beginning
or end of the line (like delete-char). If at the end of the
line, behaves identically to possible-completions. This command
is unbound by default.
complete-filename (M-/)
Attempt filename completion on the text before point.
possible-filename-completions (C-x /)
List the possible completions of the text before point, treating
it as a filename.
complete-username (M-~)
Attempt completion on the text before point, treating it as a
username.
possible-username-completions (C-x ~)
List the possible completions of the text before point, treating
it as a username.
complete-variable (M-$)
Attempt completion on the text before point, treating it as a
shell variable.
possible-variable-completions (C-x $)
List the possible completions of the text before point, treating
it as a shell variable.
complete-hostname (M-@)
Attempt completion on the text before point, treating it as a
hostname.
possible-hostname-completions (C-x @)
List the possible completions of the text before point, treating
it as a hostname.
complete-command (M-!)
Attempt completion on the text before point, treating it as a
command name. Command completion attempts to match the text
against aliases, reserved words, shell functions, shell
builtins, and finally executable filenames, in that order.
possible-command-completions (C-x !)
List the possible completions of the text before point, treating
it as a command name.
dynamic-complete-history (M-TAB)
Attempt completion on the text before point, comparing the text
against lines from the history list for possible completion
matches.
dabbrev-expand
Attempt menu completion on the text before point, comparing the
text against lines from the history list for possible completion
matches.
complete-into-braces (M-{)
Perform filename completion and insert the list of possible com-
pletions enclosed within braces so the list is available to the
shell (see Brace Expansion above).
Keyboard Macros
start-kbd-macro (C-x ()
Begin saving the characters typed into the current keyboard
macro.
end-kbd-macro (C-x ))
Stop saving the characters typed into the current keyboard macro
and store the definition.
call-last-kbd-macro (C-x e)
Re-execute the last keyboard macro defined, by making the char-
acters in the macro appear as if typed at the keyboard.
Miscellaneous
re-read-init-file (C-x C-r)
Read in the contents of the inputrc file, and incorporate any
bindings or variable assignments found there.
abort (C-g)
Abort the current editing command and ring the terminal’s bell
(subject to the setting of bell-style).
do-uppercase-version (M-a, M-b, M-x, ...)
If the metafied character x is lowercase, run the command that
is bound to the corresponding uppercase character.
prefix-meta (ESC)
Metafy the next character typed. ESC f is equivalent to Meta-f.
undo (C-_, C-x C-u)
Incremental undo, separately remembered for each line.
revert-line (M-r)
Undo all changes made to this line. This is like executing the
undo command enough times to return the line to its initial
state.
tilde-expand (M-&)
Perform tilde expansion on the current word.
set-mark (C-@, M-)
Set the mark to the point. If a numeric argument is supplied,
the mark is set to that position.
exchange-point-and-mark (C-x C-x)
Swap the point with the mark. The current cursor position is
set to the saved position, and the old cursor position is saved
as the mark.
character-search (C-])
A character is read and point is moved to the next occurrence of
that character. A negative count searches for previous occur-
rences.
character-search-backward (M-C-])
A character is read and point is moved to the previous occur-
rence of that character. A negative count searches for subse-
quent occurrences.
skip-csi-sequence ()
Read enough characters to consume a multi-key sequence such as
those defined for keys like Home and End. Such sequences begin
with a Control Sequence Indicator (CSI), usually ESC-[. If this
sequence is bound to "\[", keys producing such sequences will
have no effect unless explicitly bound to a readline command,
instead of inserting stray characters into the editing buffer.
This is unbound by default, but usually bound to ESC-[.
insert-comment (M-#)
Without a numeric argument, the value of the readline com-
ment-begin variable is inserted at the beginning of the current
line. If a numeric argument is supplied, this command acts as a
toggle: if the characters at the beginning of the line do not
match the value of comment-begin, the value is inserted, other-
wise the characters in comment-begin are deleted from the begin-
ning of the line. In either case, the line is accepted as if a
newline had been typed. The default value of comment-begin
causes this command to make the current line a shell comment.
If a numeric argument causes the comment character to be
removed, the line will be executed by the shell.
glob-complete-word (M-g)
The word before point is treated as a pattern for pathname
expansion, with an asterisk implicitly appended. This pattern
is used to generate a list of matching file names for possible
completions.
glob-expand-word (C-x *)
The word before point is treated as a pattern for pathname
expansion, and the list of matching file names is inserted,
replacing the word. If a numeric argument is supplied, an
asterisk is appended before pathname expansion.
glob-list-expansions (C-x g)
The list of expansions that would have been generated by
glob-expand-word is displayed, and the line is redrawn. If a
numeric argument is supplied, an asterisk is appended before
pathname expansion.
dump-functions
Print all of the functions and their key bindings to the read-
line output stream. If a numeric argument is supplied, the
output is formatted in such a way that it can be made part of an
inputrc file.
dump-variables
Print all of the settable readline variables and their values to
the readline output stream. If a numeric argument is supplied,
the output is formatted in such a way that it can be made part
of an inputrc file.
dump-macros
Print all of the readline key sequences bound to macros and the
strings they output. If a numeric argument is supplied, the
output is formatted in such a way that it can be made part of an
inputrc file.
display-shell-version (C-x C-v)
Display version information about the current instance of bash.
Programmable Completion
When word completion is attempted for an argument to a command for
which a completion specification (a compspec) has been defined using
the complete builtin (see SHELL BUILTIN COMMANDS below), the pro-
grammable completion facilities are invoked.
First, the command name is identified. If the command word is the
empty string (completion attempted at the beginning of an empty line),
any compspec defined with the -E option to complete is used. If a
compspec has been defined for that command, the compspec is used to
generate the list of possible completions for the word. If the command
word is a full pathname, a compspec for the full pathname is searched
for first. If no compspec is found for the full pathname, an attempt
is made to find a compspec for the portion following the final slash.
If those searches to not result in a compspec, any compspec defined
with the -D option to complete is used as the default.
Once a compspec has been found, it is used to generate the list of
matching words. If a compspec is not found, the default bash comple-
tion as described above under Completing is performed.
First, the actions specified by the compspec are used. Only matches
which are prefixed by the word being completed are returned. When the
-f or -d option is used for filename or directory name completion, the
shell variable FIGNORE is used to filter the matches.
Any completions specified by a pathname expansion pattern to the -G
option are generated next. The words generated by the pattern need not
match the word being completed. The GLOBIGNORE shell variable is not
used to filter the matches, but the FIGNORE variable is used.
Next, the string specified as the argument to the -W option is consid-
ered. The string is first split using the characters in the IFS spe-
cial variable as delimiters. Shell quoting is honored. Each word is
then expanded using brace expansion, tilde expansion, parameter and
variable expansion, command substitution, and arithmetic expansion, as
described above under EXPANSION. The results are split using the rules
described above under Word Splitting. The results of the expansion are
prefix-matched against the word being completed, and the matching words
become the possible completions.
After these matches have been generated, any shell function or command
specified with the -F and -C options is invoked. When the command or
function is invoked, the COMP_LINE, COMP_POINT, COMP_KEY, and COMP_TYPE
variables are assigned values as described above under Shell Variables.
If a shell function is being invoked, the COMP_WORDS and COMP_CWORD
variables are also set. When the function or command is invoked, the
first argument is the name of the command whose arguments are being
completed, the second argument is the word being completed, and the
third argument is the word preceding the word being completed on the
current command line. No filtering of the generated completions
against the word being completed is performed; the function or command
has complete freedom in generating the matches.
Any function specified with -F is invoked first. The function may use
any of the shell facilities, including the compgen builtin described
below, to generate the matches. It must put the possible completions
in the COMPREPLY array variable.
Next, any command specified with the -C option is invoked in an envi-
ronment equivalent to command substitution. It should print a list of
completions, one per line, to the standard output. Backslash may be
used to escape a newline, if necessary.
After all of the possible completions are generated, any filter speci-
fied with the -X option is applied to the list. The filter is a pat-
tern as used for pathname expansion; a & in the pattern is replaced
with the text of the word being completed. A literal & may be escaped
with a backslash; the backslash is removed before attempting a match.
Any completion that matches the pattern will be removed from the list.
A leading ! negates the pattern; in this case any completion not match-
ing the pattern will be removed.
Finally, any prefix and suffix specified with the -P and -S options are
added to each member of the completion list, and the result is returned
to the readline completion code as the list of possible completions.
If the previously-applied actions do not generate any matches, and the
-o dirnames option was supplied to complete when the compspec was
defined, directory name completion is attempted.
If the -o plusdirs option was supplied to complete when the compspec
was defined, directory name completion is attempted and any matches are
added to the results of the other actions.
By default, if a compspec is found, whatever it generates is returned
to the completion code as the full set of possible completions. The
default bash completions are not attempted, and the readline default of
filename completion is disabled. If the -o bashdefault option was sup-
plied to complete when the compspec was defined, the bash default com-
pletions are attempted if the compspec generates no matches. If the -o
default option was supplied to complete when the compspec was defined,
readline’s default completion will be performed if the compspec (and,
if attempted, the default bash completions) generate no matches.
When a compspec indicates that directory name completion is desired,
the programmable completion functions force readline to append a slash
to completed names which are symbolic links to directories, subject to
the value of the mark-directories readline variable, regardless of the
setting of the mark-symlinked-directories readline variable.
There is some support for dynamically modifying completions. This is
most useful when used in combination with a default completion speci-
fied with complete -D. It’s possible for shell functions executed as
completion handlers to indicate that completion should be retried by
returning an exit status of 124. If a shell function returns 124, and
changes the compspec associated with the command on which completion is
being attempted (supplied as the first argument when the function is
executed), programmable completion restarts from the beginning, with an
attempt to find a compspec for that command. This allows a set of com-
pletions to be built dynamically as completion is attempted, rather
than being loaded all at once.
For instance, assuming that there is a library of compspecs, each kept
in a file corresponding to the name of the command, the following
default completion function would load completions dynamically:
_completion_loader()
{
. "/etc/bash_completion.d/$1.sh" >/dev/null 2>&1 && return 124
}
complete -D -F _completion_loader
HISTORY
When the -o history option to the set builtin is enabled, the shell
provides access to the command history, the list of commands previously
typed. The value of the HISTSIZE variable is used as the number of
commands to save in a history list. The text of the last HISTSIZE com-
mands (default 500) is saved. The shell stores each command in the
history list prior to parameter and variable expansion (see EXPANSION
above) but after history expansion is performed, subject to the values
of the shell variables HISTIGNORE and HISTCONTROL.
On startup, the history is initialized from the file named by the vari-
able HISTFILE (default ~/.bash_history). The file named by the value
of HISTFILE is truncated, if necessary, to contain no more than the
number of lines specified by the value of HISTFILESIZE. When the his-
tory file is read, lines beginning with the history comment character
followed immediately by a digit are interpreted as timestamps for the
preceding history line. These timestamps are optionally displayed
depending on the value of the HISTTIMEFORMAT variable. When an inter-
active shell exits, the last $HISTSIZE lines are copied from the his-
tory list to $HISTFILE. If the histappend shell option is enabled (see
the description of shopt under SHELL BUILTIN COMMANDS below), the lines
are appended to the history file, otherwise the history file is over-
written. If HISTFILE is unset, or if the history file is unwritable,
the history is not saved. If the HISTTIMEFORMAT variable is set, time
stamps are written to the history file, marked with the history comment
character, so they may be preserved across shell sessions. This uses
the history comment character to distinguish timestamps from other his-
tory lines. After saving the history, the history file is truncated to
contain no more than HISTFILESIZE lines. If HISTFILESIZE is not set,
no truncation is performed.
The builtin command fc (see SHELL BUILTIN COMMANDS below) may be used
to list or edit and re-execute a portion of the history list. The his-
tory builtin may be used to display or modify the history list and
manipulate the history file. When using command-line editing, search
commands are available in each editing mode that provide access to the
history list.
The shell allows control over which commands are saved on the history
list. The HISTCONTROL and HISTIGNORE variables may be set to cause the
shell to save only a subset of the commands entered. The cmdhist shell
option, if enabled, causes the shell to attempt to save each line of a
multi-line command in the same history entry, adding semicolons where
necessary to preserve syntactic correctness. The lithist shell option
causes the shell to save the command with embedded newlines instead of
semicolons. See the description of the shopt builtin below under SHELL
BUILTIN COMMANDS for information on setting and unsetting shell
options.
HISTORY EXPANSION
The shell supports a history expansion feature that is similar to the
history expansion in csh. This section describes what syntax features
are available. This feature is enabled by default for interactive
shells, and can be disabled using the +H option to the set builtin com-
mand (see SHELL BUILTIN COMMANDS below). Non-interactive shells do not
perform history expansion by default.
History expansions introduce words from the history list into the input
stream, making it easy to repeat commands, insert the arguments to a
previous command into the current input line, or fix errors in previous
commands quickly.
History expansion is performed immediately after a complete line is
read, before the shell breaks it into words. It takes place in two
parts. The first is to determine which line from the history list to
use during substitution. The second is to select portions of that line
for inclusion into the current one. The line selected from the history
is the event, and the portions of that line that are acted upon are
words. Various modifiers are available to manipulate the selected
words. The line is broken into words in the same fashion as when read-
ing input, so that several metacharacter-separated words surrounded by
quotes are considered one word. History expansions are introduced by
the appearance of the history expansion character, which is ! by
default. Only backslash (\) and single quotes can quote the history
expansion character.
Several characters inhibit history expansion if found immediately fol-
lowing the history expansion character, even if it is unquoted: space,
tab, newline, carriage return, and =. If the extglob shell option is
enabled, ( will also inhibit expansion.
Several shell options settable with the shopt builtin may be used to
tailor the behavior of history expansion. If the histverify shell
option is enabled (see the description of the shopt builtin below), and
readline is being used, history substitutions are not immediately
passed to the shell parser. Instead, the expanded line is reloaded
into the readline editing buffer for further modification. If readline
is being used, and the histreedit shell option is enabled, a failed
history substitution will be reloaded into the readline editing buffer
for correction. The -p option to the history builtin command may be
used to see what a history expansion will do before using it. The -s
option to the history builtin may be used to add commands to the end of
the history list without actually executing them, so that they are
available for subsequent recall.
The shell allows control of the various characters used by the history
expansion mechanism (see the description of histchars above under Shell
Variables). The shell uses the history comment character to mark his-
tory timestamps when writing the history file.
Event Designators
An event designator is a reference to a command line entry in the his-
tory list.
! Start a history substitution, except when followed by a blank,
newline, carriage return, = or ( (when the extglob shell option
is enabled using the shopt builtin).
!n Refer to command line n.
!-n Refer to the current command line minus n.
!! Refer to the previous command. This is a synonym for ‘!-1’.
!string
Refer to the most recent command starting with string.
!?string[?]
Refer to the most recent command containing string. The trail-
ing ? may be omitted if string is followed immediately by a new-
line.
^string1^string2^
Quick substitution. Repeat the last command, replacing string1
with string2. Equivalent to ‘‘!!:s/string1/string2/’’ (see Mod-
ifiers below).
!# The entire command line typed so far.
Word Designators
Word designators are used to select desired words from the event. A :
separates the event specification from the word designator. It may be
omitted if the word designator begins with a ^, $, *, -, or %. Words
are numbered from the beginning of the line, with the first word being
denoted by 0 (zero). Words are inserted into the current line sepa-
rated by single spaces.
0 (zero)
The zeroth word. For the shell, this is the command word.
n The nth word.
^ The first argument. That is, word 1.
$ The last argument.
% The word matched by the most recent ‘?string?’ search.
x-y A range of words; ‘-y’ abbreviates ‘0-y’.
* All of the words but the zeroth. This is a synonym for ‘1-$’.
It is not an error to use * if there is just one word in the
event; the empty string is returned in that case.
x* Abbreviates x-$.
x- Abbreviates x-$ like x*, but omits the last word.
If a word designator is supplied without an event specification, the
previous command is used as the event.
Modifiers
After the optional word designator, there may appear a sequence of one
or more of the following modifiers, each preceded by a ‘:’.
h Remove a trailing file name component, leaving only the head.
t Remove all leading file name components, leaving the tail.
r Remove a trailing suffix of the form .xxx, leaving the basename.
e Remove all but the trailing suffix.
p Print the new command but do not execute it.
q Quote the substituted words, escaping further substitutions.
x Quote the substituted words as with q, but break into words at
blanks and newlines.
s/old/new/
Substitute new for the first occurrence of old in the event
line. Any delimiter can be used in place of /. The final
delimiter is optional if it is the last character of the event
line. The delimiter may be quoted in old and new with a single
backslash. If & appears in new, it is replaced by old. A sin-
gle backslash will quote the &. If old is null, it is set to
the last old substituted, or, if no previous history substitu-
tions took place, the last string in a !?string[?] search.
& Repeat the previous substitution.
g Cause changes to be applied over the entire event line. This is
used in conjunction with ‘:s’ (e.g., ‘:gs/old/new/’) or ‘:&’.
If used with ‘:s’, any delimiter can be used in place of /, and
the final delimiter is optional if it is the last character of
the event line. An a may be used as a synonym for g.
G Apply the following ‘s’ modifier once to each word in the event
line.
SHELL BUILTIN COMMANDS
Unless otherwise noted, each builtin command documented in this section
as accepting options preceded by - accepts -- to signify the end of the
options. The :, true, false, and test builtins do not accept options
and do not treat -- specially. The exit, logout, break, continue, let,
and shift builtins accept and process arguments beginning with - with-
out requiring --. Other builtins that accept arguments but are not
specified as accepting options interpret arguments beginning with - as
invalid options and require -- to prevent this interpretation.
: [arguments]
No effect; the command does nothing beyond expanding arguments
and performing any specified redirections. A zero exit code is
returned.
. filename [arguments]
source filename [arguments]
Read and execute commands from filename in the current shell
environment and return the exit status of the last command
executed from filename. If filename does not contain a slash,
file names in PATH are used to find the directory containing
filename. The file searched for in PATH need not be executable.
When bash is not in posix mode, the current directory is
searched if no file is found in PATH. If the sourcepath option
to the shopt builtin command is turned off, the PATH is not
searched. If any arguments are supplied, they become the posi-
tional parameters when filename is executed. Otherwise the
positional parameters are unchanged. The return status is the
status of the last command exited within the script (0 if no
commands are executed), and false if filename is not found or
cannot be read.
alias [-p] [name[=value] ...]
Alias with no arguments or with the -p option prints the list of
aliases in the form alias name=value on standard output. When
arguments are supplied, an alias is defined for each name whose
value is given. A trailing space in value causes the next word
to be checked for alias substitution when the alias is expanded.
For each name in the argument list for which no value is sup-
plied, the name and value of the alias is printed. Alias
returns true unless a name is given for which no alias has been
defined.
bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it
had been started with &. If jobspec is not present, the shell’s
notion of the current job is used. bg jobspec returns 0 unless
run when job control is disabled or, when run with job control
enabled, any specified jobspec was not found or was started
without job control.
bind [-m keymap] [-lpsvPSV]
bind [-m keymap] [-q function] [-u function] [-r keyseq]
bind [-m keymap] -f filename
bind [-m keymap] -x keyseq:shell-command
bind [-m keymap] keyseq:function-name
bind readline-command
Display current readline key and function bindings, bind a key
sequence to a readline function or macro, or set a readline
variable. Each non-option argument is a command as it would
appear in .inputrc, but each binding or command must be passed
as a separate argument; e.g., ’"\C-x\C-r": re-read-init-file’.
Options, if supplied, have the following meanings:
-m keymap
Use keymap as the keymap to be affected by the subsequent
bindings. Acceptable keymap names are emacs, emacs-stan-
dard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command,
and vi-insert. vi is equivalent to vi-command; emacs is
equivalent to emacs-standard.
-l List the names of all readline functions.
-p Display readline function names and bindings in such a
way that they can be re-read.
-P List current readline function names and bindings.
-s Display readline key sequences bound to macros and the
strings they output in such a way that they can be re-
read.
-S Display readline key sequences bound to macros and the
strings they output.
-v Display readline variable names and values in such a way
that they can be re-read.
-V List current readline variable names and values.
-f filename
Read key bindings from filename.
-q function
Query about which keys invoke the named function.
-u function
Unbind all keys bound to the named function.
-r keyseq
Remove any current binding for keyseq.
-x keyseq:shell-command
Cause shell-command to be executed whenever keyseq is
entered. When shell-command is executed, the shell sets
the READLINE_LINE variable to the contents of the read-
line line buffer and the READLINE_POINT variable to the
current location of the insertion point. If the executed
command changes the value of READLINE_LINE or READ-
LINE_POINT, those new values will be reflected in the
editing state.
The return value is 0 unless an unrecognized option is given or
an error occurred.
break [n]
Exit from within a for, while, until, or select loop. If n is
specified, break n levels. n must be ≥ 1. If n is greater than
the number of enclosing loops, all enclosing loops are exited.
The return value is non-zero when n is ≤ 0; Otherwise, break
returns 0 value.
builtin shell-builtin [arguments]
Execute the specified shell builtin, passing it arguments, and
return its exit status. This is useful when defining a function
whose name is the same as a shell builtin, retaining the func-
tionality of the builtin within the function. The cd builtin is
commonly redefined this way. The return status is false if
shell-builtin is not a shell builtin command.
caller [expr]
Returns the context of any active subroutine call (a shell func-
tion or a script executed with the . or source builtins. With-
out expr, caller displays the line number and source filename of
the current subroutine call. If a non-negative integer is sup-
plied as expr, caller displays the line number, subroutine name,
and source file corresponding to that position in the current
execution call stack. This extra information may be used, for
example, to print a stack trace. The current frame is frame 0.
The return value is 0 unless the shell is not executing a sub-
routine call or expr does not correspond to a valid position in
the call stack.
cd [-L|-P] [dir]
Change the current directory to dir. The variable HOME is the
default dir. The variable CDPATH defines the search path for
the directory containing dir. Alternative directory names in
CDPATH are separated by a colon (:). A null directory name in
CDPATH is the same as the current directory, i.e., ‘‘.’’. If
dir begins with a slash (/), then CDPATH is not used. The -P
option says to use the physical directory structure instead of
following symbolic links (see also the -P option to the set
builtin command); the -L option forces symbolic links to be fol-
lowed. An argument of - is equivalent to $OLDPWD. If a non-
empty directory name from CDPATH is used, or if - is the first
argument, and the directory change is successful, the absolute
pathname of the new working directory is written to the standard
output. The return value is true if the directory was success-
fully changed; false otherwise.
command [-pVv] command [arg ...]
Run command with args suppressing the normal shell function
lookup. Only builtin commands or commands found in the PATH are
executed. If the -p option is given, the search for command is
performed using a default value for PATH that is guaranteed to
find all of the standard utilities. If either the -V or -v
option is supplied, a description of command is printed. The -v
option causes a single word indicating the command or file name
used to invoke command to be displayed; the -V option produces a
more verbose description. If the -V or -v option is supplied,
the exit status is 0 if command was found, and 1 if not. If
neither option is supplied and an error occurred or command can-
not be found, the exit status is 127. Otherwise, the exit sta-
tus of the command builtin is the exit status of command.
compgen [option] [word]
Generate possible completion matches for word according to the
options, which may be any option accepted by the complete
builtin with the exception of -p and -r, and write the matches
to the standard output. When using the -F or -C options, the
various shell variables set by the programmable completion
facilities, while available, will not have useful values.
The matches will be generated in the same way as if the pro-
grammable completion code had generated them directly from a
completion specification with the same flags. If word is speci-
fied, only those completions matching word will be displayed.
The return value is true unless an invalid option is supplied,
or no matches were generated.
complete [-abcdefgjksuv] [-o comp-option] [-DE] [-A action] [-G glob-
pat] [-W wordlist] [-F function] [-C command]
[-X filterpat] [-P prefix] [-S suffix] name [name ...]
complete -pr [-DE] [name ...]
Specify how arguments to each name should be completed. If the
-p option is supplied, or if no options are supplied, existing
completion specifications are printed in a way that allows them
to be reused as input. The -r option removes a completion spec-
ification for each name, or, if no names are supplied, all com-
pletion specifications. The -D option indicates that the
remaining options and actions should apply to the ‘‘default’’
command completion; that is, completion attempted on a command
for which no completion has previously been defined. The -E
option indicates that the remaining options and actions should
apply to ‘‘empty’’ command completion; that is, completion
attempted on a blank line.
The process of applying these completion specifications when
word completion is attempted is described above under Pro-
grammable Completion.
Other options, if specified, have the following meanings. The
arguments to the -G, -W, and -X options (and, if necessary, the
-P and -S options) should be quoted to protect them from expan-
sion before the complete builtin is invoked.
-o comp-option
The comp-option controls several aspects of the comp-
spec’s behavior beyond the simple generation of comple-
tions. comp-option may be one of:
bashdefault
Perform the rest of the default bash completions
if the compspec generates no matches.
default Use readline’s default filename completion if
the compspec generates no matches.
dirnames
Perform directory name completion if the comp-
spec generates no matches.
filenames
Tell readline that the compspec generates file-
names, so it can perform any filename-specific
processing (like adding a slash to directory
names, quoting special characters, or suppress-
ing trailing spaces). Intended to be used with
shell functions.
nospace Tell readline not to append a space (the
default) to words completed at the end of the
line.
plusdirs
After any matches defined by the compspec are
generated, directory name completion is
attempted and any matches are added to the
results of the other actions.
-A action
The action may be one of the following to generate a
list of possible completions:
alias Alias names. May also be specified as -a.
arrayvar
Array variable names.
binding Readline key binding names.
builtin Names of shell builtin commands. May also be
specified as -b.
command Command names. May also be specified as -c.
directory
Directory names. May also be specified as -d.
disabled
Names of disabled shell builtins.
enabled Names of enabled shell builtins.
export Names of exported shell variables. May also be
specified as -e.
file File names. May also be specified as -f.
function
Names of shell functions.
group Group names. May also be specified as -g.
helptopic
Help topics as accepted by the help builtin.
hostname
Hostnames, as taken from the file specified by
the HOSTFILE shell variable.
job Job names, if job control is active. May also
be specified as -j.
keyword Shell reserved words. May also be specified as
-k.
running Names of running jobs, if job control is active.
service Service names. May also be specified as -s.
setopt Valid arguments for the -o option to the set
builtin.
shopt Shell option names as accepted by the shopt
builtin.
signal Signal names.
stopped Names of stopped jobs, if job control is active.
user User names. May also be specified as -u.
variable
Names of all shell variables. May also be spec-
ified as -v.
-G globpat
The pathname expansion pattern globpat is expanded to
generate the possible completions.
-W wordlist
The wordlist is split using the characters in the IFS
special variable as delimiters, and each resultant word
is expanded. The possible completions are the members
of the resultant list which match the word being com-
pleted.
-C command
command is executed in a subshell environment, and its
output is used as the possible completions.
-F function
The shell function function is executed in the current
shell environment. When it finishes, the possible com-
pletions are retrieved from the value of the COMPREPLY
array variable.
-X filterpat
filterpat is a pattern as used for pathname expansion.
It is applied to the list of possible completions gener-
ated by the preceding options and arguments, and each
completion matching filterpat is removed from the list.
A leading ! in filterpat negates the pattern; in this
case, any completion not matching filterpat is removed.
-P prefix
prefix is added at the beginning of each possible com-
pletion after all other options have been applied.
-S suffix
suffix is appended to each possible completion after all
other options have been applied.
The return value is true unless an invalid option is supplied,
an option other than -p or -r is supplied without a name argu-
ment, an attempt is made to remove a completion specification
for a name for which no specification exists, or an error occurs
adding a completion specification.
compopt [-o option] [-DE] [+o option] [name]
Modify completion options for each name according to the
options, or for the currently-execution completion if no names
are supplied. If no options are given, display the completion
options for each name or the current completion. The possible
values of option are those valid for the complete builtin
described above. The -D option indicates that the remaining
options should apply to the ‘‘default’’ command completion; that
is, completion attempted on a command for which no completion
has previously been defined. The -E option indicates that the
remaining options should apply to ‘‘empty’’ command completion;
that is, completion attempted on a blank line.
The return value is true unless an invalid option is supplied, an
attempt is made to modify the options for a name for which no comple-
tion specification exists, or an output error occurs.
continue [n]
Resume the next iteration of the enclosing for, while, until, or
select loop. If n is specified, resume at the nth enclosing
loop. n must be ≥ 1. If n is greater than the number of
enclosing loops, the last enclosing loop (the ‘‘top-level’’
loop) is resumed. When continue is executed inside of loop, the
return value is non-zero when n is ≤ 0; Otherwise, continue
returns 0 value. When continue is executed outside of loop, the
return value is 0.
declare [-aAfFilrtux] [-p] [name[=value] ...]
typeset [-aAfFilrtux] [-p] [name[=value] ...]
Declare variables and/or give them attributes. If no names are
given then display the values of variables. The -p option will
display the attributes and values of each name. When -p is used
with name arguments, additional options are ignored. When -p is
supplied without name arguments, it will display the attributes
and values of all variables having the attributes specified by
the additional options. If no other options are supplied with
-p, declare will display the attributes and values of all shell
variables. The -f option will restrict the display to shell
functions. The -F option inhibits the display of function defi-
nitions; only the function name and attributes are printed. If
the extdebug shell option is enabled using shopt, the source
file name and line number where the function is defined are dis-
played as well. The -F option implies -f. The following
options can be used to restrict output to variables with the
specified attribute or to give variables attributes:
-a Each name is an indexed array variable (see Arrays
above).
-A Each name is an associative array variable (see Arrays
above).
-f Use function names only.
-i The variable is treated as an integer; arithmetic evalua-
tion (see ARITHMETIC EVALUATION above) is performed when
the variable is assigned a value.
-l When the variable is assigned a value, all upper-case
characters are converted to lower-case. The upper-case
attribute is disabled.
-r Make names readonly. These names cannot then be assigned
values by subsequent assignment statements or unset.
-t Give each name the trace attribute. Traced functions
inherit the DEBUG and RETURN traps from the calling
shell. The trace attribute has no special meaning for
variables.
-u When the variable is assigned a value, all lower-case
characters are converted to upper-case. The lower-case
attribute is disabled.
-x Mark names for export to subsequent commands via the
environment.
Using ‘+’ instead of ‘-’ turns off the attribute instead, with
the exceptions that +a may not be used to destroy an array vari-
able and +r will not remove the readonly attribute. When used
in a function, makes each name local, as with the local command.
If a variable name is followed by =value, the value of the vari-
able is set to value. The return value is 0 unless an invalid
option is encountered, an attempt is made to define a function
using ‘‘-f foo=bar’’, an attempt is made to assign a value to a
readonly variable, an attempt is made to assign a value to an
array variable without using the compound assignment syntax (see
Arrays above), one of the names is not a valid shell variable
name, an attempt is made to turn off readonly status for a read-
only variable, an attempt is made to turn off array status for
an array variable, or an attempt is made to display a non-exis-
tent function with -f.
dirs [+n] [-n] [-cplv]
Without options, displays the list of currently remembered
directories. The default display is on a single line with
directory names separated by spaces. Directories are added to
the list with the pushd command; the popd command removes
entries from the list.
+n Displays the nth entry counting from the left of the list
shown by dirs when invoked without options, starting with
zero.
-n Displays the nth entry counting from the right of the
list shown by dirs when invoked without options, starting
with zero.
-c Clears the directory stack by deleting all of the
entries.
-l Produces a longer listing; the default listing format
uses a tilde to denote the home directory.
-p Print the directory stack with one entry per line.
-v Print the directory stack with one entry per line, pre-
fixing each entry with its index in the stack.
The return value is 0 unless an invalid option is supplied or n
indexes beyond the end of the directory stack.
disown [-ar] [-h] [jobspec ...]
Without options, each jobspec is removed from the table of
active jobs. If jobspec is not present, and neither -a nor -r
is supplied, the shell’s notion of the current job is used. If
the -h option is given, each jobspec is not removed from the ta-
ble, but is marked so that SIGHUP is not sent to the job if the
shell receives a SIGHUP. If no jobspec is present, and neither
the -a nor the -r option is supplied, the current job is used.
If no jobspec is supplied, the -a option means to remove or mark
all jobs; the -r option without a jobspec argument restricts
operation to running jobs. The return value is 0 unless a job-
spec does not specify a valid job.
echo [-neE] [arg ...]
Output the args, separated by spaces, followed by a newline.
The return status is always 0. If -n is specified, the trailing
newline is suppressed. If the -e option is given, interpreta-
tion of the following backslash-escaped characters is enabled.
The -E option disables the interpretation of these escape char-
acters, even on systems where they are interpreted by default.
The xpg_echo shell option may be used to dynamically determine
whether or not echo expands these escape characters by default.
echo does not interpret -- to mean the end of options. echo
interprets the following escape sequences:
\a alert (bell)
\b backspace
\c suppress further output
\e an escape character
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\0nnn the eight-bit character whose value is the octal value
nnn (zero to three octal digits)
\xHH the eight-bit character whose value is the hexadecimal
value HH (one or two hex digits)
enable [-a] [-dnps] [-f filename] [name ...]
Enable and disable builtin shell commands. Disabling a builtin
allows a disk command which has the same name as a shell builtin
to be executed without specifying a full pathname, even though
the shell normally searches for builtins before disk commands.
If -n is used, each name is disabled; otherwise, names are
enabled. For example, to use the test binary found via the PATH
instead of the shell builtin version, run ‘‘enable -n test’’.
The -f option means to load the new builtin command name from
shared object filename, on systems that support dynamic loading.
The -d option will delete a builtin previously loaded with -f.
If no name arguments are given, or if the -p option is supplied,
a list of shell builtins is printed. With no other option argu-
ments, the list consists of all enabled shell builtins. If -n
is supplied, only disabled builtins are printed. If -a is sup-
plied, the list printed includes all builtins, with an indica-
tion of whether or not each is enabled. If -s is supplied, the
output is restricted to the POSIX special builtins. The return
value is 0 unless a name is not a shell builtin or there is an
error loading a new builtin from a shared object.
eval [arg ...]
The args are read and concatenated together into a single com-
mand. This command is then read and executed by the shell, and
its exit status is returned as the value of eval. If there are
no args, or only null arguments, eval returns 0.
exec [-cl] [-a name] [command [arguments]]
If command is specified, it replaces the shell. No new process
is created. The arguments become the arguments to command. If
the -l option is supplied, the shell places a dash at the begin-
ning of the zeroth argument passed to command. This is what
login(1) does. The -c option causes command to be executed with
an empty environment. If -a is supplied, the shell passes name
as the zeroth argument to the executed command. If command can-
not be executed for some reason, a non-interactive shell exits,
unless the shell option execfail is enabled, in which case it
returns failure. An interactive shell returns failure if the
file cannot be executed. If command is not specified, any redi-
rections take effect in the current shell, and the return status
is 0. If there is a redirection error, the return status is 1.
exit [n]
Cause the shell to exit with a status of n. If n is omitted,
the exit status is that of the last command executed. A trap on
EXIT is executed before the shell terminates.
export [-fn] [name[=word]] ...
export -p
The supplied names are marked for automatic export to the envi-
ronment of subsequently executed commands. If the -f option is
given, the names refer to functions. If no names are given, or
if the -p option is supplied, a list of all names that are
exported in this shell is printed. The -n option causes the
export property to be removed from each name. If a variable
name is followed by =word, the value of the variable is set to
word. export returns an exit status of 0 unless an invalid
option is encountered, one of the names is not a valid shell
variable name, or -f is supplied with a name that is not a func-
tion.
fc [-e ename] [-lnr] [first] [last]
fc -s [pat=rep] [cmd]
Fix Command. In the first form, a range of commands from first
to last is selected from the history list. First and last may
be specified as a string (to locate the last command beginning
with that string) or as a number (an index into the history
list, where a negative number is used as an offset from the cur-
rent command number). If last is not specified it is set to the
current command for listing (so that ‘‘fc -l -10’’ prints the
last 10 commands) and to first otherwise. If first is not spec-
ified it is set to the previous command for editing and -16 for
listing.
The -n option suppresses the command numbers when listing. The
-r option reverses the order of the commands. If the -l option
is given, the commands are listed on standard output. Other-
wise, the editor given by ename is invoked on a file containing
those commands. If ename is not given, the value of the FCEDIT
variable is used, and the value of EDITOR if FCEDIT is not set.
If neither variable is set, vi is used. When editing is com-
plete, the edited commands are echoed and executed.
In the second form, command is re-executed after each instance
of pat is replaced by rep. A useful alias to use with this is
‘‘r="fc -s"’’, so that typing ‘‘r cc’’ runs the last command
beginning with ‘‘cc’’ and typing ‘‘r’’ re-executes the last com-
mand.
If the first form is used, the return value is 0 unless an
invalid option is encountered or first or last specify history
lines out of range. If the -e option is supplied, the return
value is the value of the last command executed or failure if an
error occurs with the temporary file of commands. If the second
form is used, the return status is that of the command re-exe-
cuted, unless cmd does not specify a valid history line, in
which case fc returns failure.
fg [jobspec]
Resume jobspec in the foreground, and make it the current job.
If jobspec is not present, the shell’s notion of the current job
is used. The return value is that of the command placed into
the foreground, or failure if run when job control is disabled
or, when run with job control enabled, if jobspec does not spec-
ify a valid job or jobspec specifies a job that was started
without job control.
getopts optstring name [args]
getopts is used by shell procedures to parse positional parame-
ters. optstring contains the option characters to be recog-
nized; if a character is followed by a colon, the option is
expected to have an argument, which should be separated from it
by white space. The colon and question mark characters may not
be used as option characters. Each time it is invoked, getopts
places the next option in the shell variable name, initializing
name if it does not exist, and the index of the next argument to
be processed into the variable OPTIND. OPTIND is initialized to
1 each time the shell or a shell script is invoked. When an
option requires an argument, getopts places that argument into
the variable OPTARG. The shell does not reset OPTIND automati-
cally; it must be manually reset between multiple calls to
getopts within the same shell invocation if a new set of parame-
ters is to be used.
When the end of options is encountered, getopts exits with a
return value greater than zero. OPTIND is set to the index of
the first non-option argument, and name is set to ?.
getopts normally parses the positional parameters, but if more
arguments are given in args, getopts parses those instead.
getopts can report errors in two ways. If the first character
of optstring is a colon, silent error reporting is used. In
normal operation diagnostic messages are printed when invalid
options or missing option arguments are encountered. If the
variable OPTERR is set to 0, no error messages will be dis-
played, even if the first character of optstring is not a colon.
If an invalid option is seen, getopts places ? into name and, if
not silent, prints an error message and unsets OPTARG. If
getopts is silent, the option character found is placed in
OPTARG and no diagnostic message is printed.
If a required argument is not found, and getopts is not silent,
a question mark (?) is placed in name, OPTARG is unset, and a
diagnostic message is printed. If getopts is silent, then a
colon (:) is placed in name and OPTARG is set to the option
character found.
getopts returns true if an option, specified or unspecified, is
found. It returns false if the end of options is encountered or
an error occurs.
hash [-lr] [-p filename] [-dt] [name]
For each name, the full file name of the command is determined
by searching the directories in $PATH and remembered. If the -p
option is supplied, no path search is performed, and filename is
used as the full file name of the command. The -r option causes
the shell to forget all remembered locations. The -d option
causes the shell to forget the remembered location of each name.
If the -t option is supplied, the full pathname to which each
name corresponds is printed. If multiple name arguments are
supplied with -t, the name is printed before the hashed full
pathname. The -l option causes output to be displayed in a for-
mat that may be reused as input. If no arguments are given, or
if only -l is supplied, information about remembered commands is
printed. The return status is true unless a name is not found
or an invalid option is supplied.
help [-dms] [pattern]
Display helpful information about builtin commands. If pattern
is specified, help gives detailed help on all commands matching
pattern; otherwise help for all the builtins and shell control
structures is printed.
-d Display a short description of each pattern
-m Display the description of each pattern in a manpage-like
format
-s Display only a short usage synopsis for each pattern
The return status is 0 unless no command matches pattern.
history [n]
history -c
history -d offset
history -anrw [filename]
history -p arg [arg ...]
history -s arg [arg ...]
With no options, display the command history list with line num-
bers. Lines listed with a * have been modified. An argument of
n lists only the last n lines. If the shell variable HISTTIME-
FORMAT is set and not null, it is used as a format string for
strftime(3) to display the time stamp associated with each dis-
played history entry. No intervening blank is printed between
the formatted time stamp and the history line. If filename is
supplied, it is used as the name of the history file; if not,
the value of HISTFILE is used. Options, if supplied, have the
following meanings:
-c Clear the history list by deleting all the entries.
-d offset
Delete the history entry at position offset.
-a Append the ‘‘new’’ history lines (history lines entered
since the beginning of the current bash session) to the
history file.
-n Read the history lines not already read from the history
file into the current history list. These are lines
appended to the history file since the beginning of the
current bash session.
-r Read the contents of the history file and use them as the
current history.
-w Write the current history to the history file, overwrit-
ing the history file’s contents.
-p Perform history substitution on the following args and
display the result on the standard output. Does not
store the results in the history list. Each arg must be
quoted to disable normal history expansion.
-s Store the args in the history list as a single entry.
The last command in the history list is removed before
the args are added.
If the HISTTIMEFORMAT variable is set, the time stamp informa-
tion associated with each history entry is written to the his-
tory file, marked with the history comment character. When the
history file is read, lines beginning with the history comment
character followed immediately by a digit are interpreted as
timestamps for the previous history line. The return value is 0
unless an invalid option is encountered, an error occurs while
reading or writing the history file, an invalid offset is sup-
plied as an argument to -d, or the history expansion supplied as
an argument to -p fails.
jobs [-lnprs] [ jobspec ... ]
jobs -x command [ args ... ]
The first form lists the active jobs. The options have the fol-
lowing meanings:
-l List process IDs in addition to the normal information.
-p List only the process ID of the job’s process group
leader.
-n Display information only about jobs that have changed
status since the user was last notified of their status.
-r Restrict output to running jobs.
-s Restrict output to stopped jobs.
If jobspec is given, output is restricted to information about
that job. The return status is 0 unless an invalid option is
encountered or an invalid jobspec is supplied.
If the -x option is supplied, jobs replaces any jobspec found in
command or args with the corresponding process group ID, and
executes command passing it args, returning its exit status.
kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ...
kill -l [sigspec | exit_status]
Send the signal named by sigspec or signum to the processes
named by pid or jobspec. sigspec is either a case-insensitive
signal name such as SIGKILL (with or without the SIG prefix) or
a signal number; signum is a signal number. If sigspec is not
present, then SIGTERM is assumed. An argument of -l lists the
signal names. If any arguments are supplied when -l is given,
the names of the signals corresponding to the arguments are
listed, and the return status is 0. The exit_status argument to
-l is a number specifying either a signal number or the exit
status of a process terminated by a signal. kill returns true
if at least one signal was successfully sent, or false if an
error occurs or an invalid option is encountered.
let arg [arg ...]
Each arg is an arithmetic expression to be evaluated (see ARITH-
METIC EVALUATION above). If the last arg evaluates to 0, let
returns 1; 0 is returned otherwise.
local [option] [name[=value] ...]
For each argument, a local variable named name is created, and
assigned value. The option can be any of the options accepted
by declare. When local is used within a function, it causes the
variable name to have a visible scope restricted to that func-
tion and its children. With no operands, local writes a list of
local variables to the standard output. It is an error to use
local when not within a function. The return status is 0 unless
local is used outside a function, an invalid name is supplied,
or name is a readonly variable.
logout Exit a login shell.
mapfile [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback]
[-c quantum] [array]
readarray [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback]
[-c quantum] [array]
Read lines from the standard input into the indexed array vari-
able array, or from file descriptor fd if the -u option is sup-
plied. The variable MAPFILE is the default array. Options, if
supplied, have the following meanings:
-n Copy at most count lines. If count is 0, all lines are
copied.
-O Begin assigning to array at index origin. The default
index is 0.
-s Discard the first count lines read.
-t Remove a trailing newline from each line read.
-u Read lines from file descriptor fd instead of the stan-
dard input.
-C Evaluate callback each time quantum lines are read. The
-c option specifies quantum.
-c Specify the number of lines read between each call to
callback.
If -C is specified without -c, the default quantum is 5000.
When callback is evaluated, it is supplied the index of the next
array element to be assigned as an additional argument. call-
back is evaluated after the line is read but before the array
element is assigned.
If not supplied with an explicit origin, mapfile will clear
array before assigning to it.
mapfile returns successfully unless an invalid option or option
argument is supplied, array is invalid or unassignable, or if
array is not an indexed array.
popd [-n] [+n] [-n]
Removes entries from the directory stack. With no arguments,
removes the top directory from the stack, and performs a cd to
the new top directory. Arguments, if supplied, have the follow-
ing meanings:
-n Suppresses the normal change of directory when removing
directories from the stack, so that only the stack is
manipulated.
+n Removes the nth entry counting from the left of the list
shown by dirs, starting with zero. For example: ‘‘popd
+0’’ removes the first directory, ‘‘popd +1’’ the second.
-n Removes the nth entry counting from the right of the list
shown by dirs, starting with zero. For example: ‘‘popd
-0’’ removes the last directory, ‘‘popd -1’’ the next to
last.
If the popd command is successful, a dirs is performed as well,
and the return status is 0. popd returns false if an invalid
option is encountered, the directory stack is empty, a non-exis-
tent directory stack entry is specified, or the directory change
fails.
printf [-v var] format [arguments]
Write the formatted arguments to the standard output under the
control of the format. The format is a character string which
contains three types of objects: plain characters, which are
simply copied to standard output, character escape sequences,
which are converted and copied to the standard output, and for-
mat specifications, each of which causes printing of the next
successive argument. In addition to the standard printf(1) for-
mats, %b causes printf to expand backslash escape sequences in
the corresponding argument (except that \c terminates output,
backslashes in \', \", and \? are not removed, and octal escapes
beginning with \0 may contain up to four digits), and %q causes
printf to output the corresponding argument in a format that can
be reused as shell input.
The -v option causes the output to be assigned to the variable
var rather than being printed to the standard output.
The format is reused as necessary to consume all of the argu-
ments. If the format requires more arguments than are supplied,
the extra format specifications behave as if a zero value or
null string, as appropriate, had been supplied. The return
value is zero on success, non-zero on failure.
pushd [-n] [+n] [-n]
pushd [-n] [dir]
Adds a directory to the top of the directory stack, or rotates
the stack, making the new top of the stack the current working
directory. With no arguments, exchanges the top two directories
and returns 0, unless the directory stack is empty. Arguments,
if supplied, have the following meanings:
-n Suppresses the normal change of directory when adding
directories to the stack, so that only the stack is
manipulated.
+n Rotates the stack so that the nth directory (counting
from the left of the list shown by dirs, starting with
zero) is at the top.
-n Rotates the stack so that the nth directory (counting
from the right of the list shown by dirs, starting with
zero) is at the top.
dir Adds dir to the directory stack at the top, making it the
new current working directory.
If the pushd command is successful, a dirs is performed as well.
If the first form is used, pushd returns 0 unless the cd to dir
fails. With the second form, pushd returns 0 unless the direc-
tory stack is empty, a non-existent directory stack element is
specified, or the directory change to the specified new current
directory fails.
pwd [-LP]
Print the absolute pathname of the current working directory.
The pathname printed contains no symbolic links if the -P option
is supplied or the -o physical option to the set builtin command
is enabled. If the -L option is used, the pathname printed may
contain symbolic links. The return status is 0 unless an error
occurs while reading the name of the current directory or an
invalid option is supplied.
read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p
prompt] [-t timeout] [-u fd] [name ...]
One line is read from the standard input, or from the file
descriptor fd supplied as an argument to the -u option, and the
first word is assigned to the first name, the second word to the
second name, and so on, with leftover words and their interven-
ing separators assigned to the last name. If there are fewer
words read from the input stream than names, the remaining names
are assigned empty values. The characters in IFS are used to
split the line into words. The backslash character (\) may be
used to remove any special meaning for the next character read
and for line continuation. Options, if supplied, have the fol-
lowing meanings:
-a aname
The words are assigned to sequential indices of the array
variable aname, starting at 0. aname is unset before any
new values are assigned. Other name arguments are
ignored.
-d delim
The first character of delim is used to terminate the
input line, rather than newline.
-e If the standard input is coming from a terminal, readline
(see READLINE above) is used to obtain the line. Read-
line uses the current (or default, if line editing was
not previously active) editing settings.
-i text
If readline is being used to read the line, text is
placed into the editing buffer before editing begins.
-n nchars
read returns after reading nchars characters rather than
waiting for a complete line of input, but honor a delim-
iter if fewer than nchars characters are read before the
delimiter.
-N nchars
read returns after reading exactly nchars characters
rather than waiting for a complete line of input, unless
EOF is encountered or read times out. Delimiter charac-
ters encountered in the input are not treated specially
and do not cause read to return until nchars characters
are read.
-p prompt
Display prompt on standard error, without a trailing new-
line, before attempting to read any input. The prompt is
displayed only if input is coming from a terminal.
-r Backslash does not act as an escape character. The back-
slash is considered to be part of the line. In particu-
lar, a backslash-newline pair may not be used as a line
continuation.
-s Silent mode. If input is coming from a terminal, charac-
ters are not echoed.
-t timeout
Cause read to time out and return failure if a complete
line of input is not read within timeout seconds. time-
out may be a decimal number with a fractional portion
following the decimal point. This option is only effec-
tive if read is reading input from a terminal, pipe, or
other special file; it has no effect when reading from
regular files. If timeout is 0, read returns success if
input is available on the specified file descriptor,
failure otherwise. The exit status is greater than 128
if the timeout is exceeded.
-u fd Read input from file descriptor fd.
If no names are supplied, the line read is assigned to the vari-
able REPLY. The return code is zero, unless end-of-file is
encountered, read times out (in which case the return code is
greater than 128), or an invalid file descriptor is supplied as
the argument to -u.
readonly [-aApf] [name[=word] ...]
The given names are marked readonly; the values of these names
may not be changed by subsequent assignment. If the -f option
is supplied, the functions corresponding to the names are so
marked. The -a option restricts the variables to indexed
arrays; the -A option restricts the variables to associative
arrays. If no name arguments are given, or if the -p option is
supplied, a list of all readonly names is printed. The -p
option causes output to be displayed in a format that may be
reused as input. If a variable name is followed by =word, the
value of the variable is set to word. The return status is 0
unless an invalid option is encountered, one of the names is not
a valid shell variable name, or -f is supplied with a name that
is not a function.
return [n]
Causes a function to exit with the return value specified by n.
If n is omitted, the return status is that of the last command
executed in the function body. If used outside a function, but
during execution of a script by the . (source) command, it
causes the shell to stop executing that script and return either
n or the exit status of the last command executed within the
script as the exit status of the script. If used outside a
function and not during execution of a script by ., the return
status is false. Any command associated with the RETURN trap is
executed before execution resumes after the function or script.
set [--abefhkmnptuvxBCEHPT] [-o option] [arg ...]
set [+abefhkmnptuvxBCEHPT] [+o option] [arg ...]
Without options, the name and value of each shell variable are
displayed in a format that can be reused as input for setting or
resetting the currently-set variables. Read-only variables can-
not be reset. In posix mode, only shell variables are listed.
The output is sorted according to the current locale. When
options are specified, they set or unset shell attributes. Any
arguments remaining after option processing are treated as val-
ues for the positional parameters and are assigned, in order, to
$1, $2, ... $n. Options, if specified, have the following
meanings:
-a Automatically mark variables and functions which are
modified or created for export to the environment of
subsequent commands.
-b Report the status of terminated background jobs immedi-
ately, rather than before the next primary prompt. This
is effective only when job control is enabled.
-e Exit immediately if a pipeline (which may consist of a
single simple command), a subshell command enclosed in
parentheses, or one of the commands executed as part of
a command list enclosed by braces (see SHELL GRAMMAR
above) exits with a non-zero status. The shell does not
exit if the command that fails is part of the command
list immediately following a while or until keyword,
part of the test following the if or elif reserved
words, part of any command executed in a && or ││ list
except the command following the final && or ││, any
command in a pipeline but the last, or if the command’s
return value is being inverted with !. A trap on ERR,
if set, is executed before the shell exits. This option
applies to the shell environment and each subshell envi-
ronment separately (see COMMAND EXECUTION ENVIRONMENT
above), and may cause subshells to exit before executing
all the commands in the subshell.
-f Disable pathname expansion.
-h Remember the location of commands as they are looked up
for execution. This is enabled by default.
-k All arguments in the form of assignment statements are
placed in the environment for a command, not just those
that precede the command name.
-m Monitor mode. Job control is enabled. This option is
on by default for interactive shells on systems that
support it (see JOB CONTROL above). Background pro-
cesses run in a separate process group and a line con-
taining their exit status is printed upon their comple-
tion.
-n Read commands but do not execute them. This may be used
to check a shell script for syntax errors. This is
ignored by interactive shells.
-o option-name
The option-name can be one of the following:
allexport
Same as -a.
braceexpand
Same as -B.
emacs Use an emacs-style command line editing inter-
face. This is enabled by default when the shell
is interactive, unless the shell is started with
the --noediting option. This also affects the
editing interface used for read -e.
errexit Same as -e.
errtrace
Same as -E.
functrace
Same as -T.
hashall Same as -h.
histexpand
Same as -H.
history Enable command history, as described above under
HISTORY. This option is on by default in inter-
active shells.
ignoreeof
The effect is as if the shell command
‘‘IGNOREEOF=10’’ had been executed (see Shell
Variables above).
keyword Same as -k.
monitor Same as -m.
noclobber
Same as -C.
noexec Same as -n.
noglob Same as -f.
nolog Currently ignored.
notify Same as -b.
nounset Same as -u.
onecmd Same as -t.
physical
Same as -P.
pipefail
If set, the return value of a pipeline is the
value of the last (rightmost) command to exit
with a non-zero status, or zero if all commands
in the pipeline exit successfully. This option
is disabled by default.
posix Change the behavior of bash where the default
operation differs from the POSIX standard to
match the standard (posix mode).
privileged
Same as -p.
verbose Same as -v.
vi Use a vi-style command line editing interface.
This also affects the editing interface used for
read -e.
xtrace Same as -x.
If -o is supplied with no option-name, the values of the
current options are printed. If +o is supplied with no
option-name, a series of set commands to recreate the
current option settings is displayed on the standard
output.
-p Turn on privileged mode. In this mode, the $ENV and
$BASH_ENV files are not processed, shell functions are
not inherited from the environment, and the SHELLOPTS,
BASHOPTS, CDPATH, and GLOBIGNORE variables, if they
appear in the environment, are ignored. If the shell is
started with the effective user (group) id not equal to
the real user (group) id, and the -p option is not sup-
plied, these actions are taken and the effective user id
is set to the real user id. If the -p option is sup-
plied at startup, the effective user id is not reset.
Turning this option off causes the effective user and
group ids to be set to the real user and group ids.
-t Exit after reading and executing one command.
-u Treat unset variables and parameters other than the spe-
cial parameters "@" and "*" as an error when performing
parameter expansion. If expansion is attempted on an
unset variable or parameter, the shell prints an error
message, and, if not interactive, exits with a non-zero
status.
-v Print shell input lines as they are read.
-x After expanding each simple command, for command, case
command, select command, or arithmetic for command, dis-
play the expanded value of PS4, followed by the command
and its expanded arguments or associated word list.
-B The shell performs brace expansion (see Brace Expansion
above). This is on by default.
-C If set, bash does not overwrite an existing file with
the >, >&, and <> redirection operators. This may be
overridden when creating output files by using the redi-
rection operator >| instead of >.
-E If set, any trap on ERR is inherited by shell functions,
command substitutions, and commands executed in a sub-
shell environment. The ERR trap is normally not inher-
ited in such cases.
-H Enable ! style history substitution. This option is on
by default when the shell is interactive.
-P If set, the shell does not follow symbolic links when
executing commands such as cd that change the current
working directory. It uses the physical directory
structure instead. By default, bash follows the logical
chain of directories when performing commands which
change the current directory.
-T If set, any traps on DEBUG and RETURN are inherited by
shell functions, command substitutions, and commands
executed in a subshell environment. The DEBUG and
RETURN traps are normally not inherited in such cases.
-- If no arguments follow this option, then the positional
parameters are unset. Otherwise, the positional parame-
ters are set to the args, even if some of them begin
with a -.
- Signal the end of options, cause all remaining args to
be assigned to the positional parameters. The -x and -v
options are turned off. If there are no args, the posi-
tional parameters remain unchanged.
The options are off by default unless otherwise noted. Using +
rather than - causes these options to be turned off. The
options can also be specified as arguments to an invocation of
the shell. The current set of options may be found in $-. The
return status is always true unless an invalid option is encoun-
tered.
shift [n]
The positional parameters from n+1 ... are renamed to $1 ....
Parameters represented by the numbers $# down to $#-n+1 are
unset. n must be a non-negative number less than or equal to
$#. If n is 0, no parameters are changed. If n is not given,
it is assumed to be 1. If n is greater than $#, the positional
parameters are not changed. The return status is greater than
zero if n is greater than $# or less than zero; otherwise 0.
shopt [-pqsu] [-o] [optname ...]
Toggle the values of variables controlling optional shell behav-
ior. With no options, or with the -p option, a list of all set-
table options is displayed, with an indication of whether or not
each is set. The -p option causes output to be displayed in a
form that may be reused as input. Other options have the fol-
lowing meanings:
-s Enable (set) each optname.
-u Disable (unset) each optname.
-q Suppresses normal output (quiet mode); the return status
indicates whether the optname is set or unset. If multi-
ple optname arguments are given with -q, the return sta-
tus is zero if all optnames are enabled; non-zero other-
wise.
-o Restricts the values of optname to be those defined for
the -o option to the set builtin.
If either -s or -u is used with no optname arguments, the dis-
play is limited to those options which are set or unset, respec-
tively. Unless otherwise noted, the shopt options are disabled
(unset) by default.
The return status when listing options is zero if all optnames
are enabled, non-zero otherwise. When setting or unsetting
options, the return status is zero unless an optname is not a
valid shell option.
The list of shopt options is:
autocd If set, a command name that is the name of a directory
is executed as if it were the argument to the cd com-
mand. This option is only used by interactive shells.
cdable_vars
If set, an argument to the cd builtin command that is
not a directory is assumed to be the name of a variable
whose value is the directory to change to.
cdspell If set, minor errors in the spelling of a directory com-
ponent in a cd command will be corrected. The errors
checked for are transposed characters, a missing charac-
ter, and one character too many. If a correction is
found, the corrected file name is printed, and the com-
mand proceeds. This option is only used by interactive
shells.
checkhash
If set, bash checks that a command found in the hash ta-
ble exists before trying to execute it. If a hashed
command no longer exists, a normal path search is per-
formed.
checkjobs
If set, bash lists the status of any stopped and running
jobs before exiting an interactive shell. If any jobs
are running, this causes the exit to be deferred until a
second exit is attempted without an intervening command
(see JOB CONTROL above). The shell always postpones
exiting if any jobs are stopped.
checkwinsize
If set, bash checks the window size after each command
and, if necessary, updates the values of LINES and
COLUMNS.
cmdhist If set, bash attempts to save all lines of a multiple-
line command in the same history entry. This allows
easy re-editing of multi-line commands.
compat31
If set, bash changes its behavior to that of version 3.1
with respect to quoted arguments to the conditional
command’s =~ operator.
compat32
If set, bash changes its behavior to that of version 3.2
with respect to locale-specific string comparison when
using the conditional command’s < and > operators.
compat40
If set, bash changes its behavior to that of version 4.0
with respect to locale-specific string comparison when
using the conditional command’s < and > operators and
the effect of interrupting a command list.
dirspell
If set, bash attempts spelling correction on directory
names during word completion if the directory name ini-
tially supplied does not exist.
dotglob If set, bash includes filenames beginning with a ‘.’ in
the results of pathname expansion.
execfail
If set, a non-interactive shell will not exit if it can-
not execute the file specified as an argument to the
exec builtin command. An interactive shell does not
exit if exec fails.
expand_aliases
If set, aliases are expanded as described above under
ALIASES. This option is enabled by default for interac-
tive shells.
extdebug
If set, behavior intended for use by debuggers is
enabled:
1. The -F option to the declare builtin displays the
source file name and line number corresponding to
each function name supplied as an argument.
2. If the command run by the DEBUG trap returns a
non-zero value, the next command is skipped and
not executed.
3. If the command run by the DEBUG trap returns a
value of 2, and the shell is executing in a sub-
routine (a shell function or a shell script exe-
cuted by the . or source builtins), a call to
return is simulated.
4. BASH_ARGC and BASH_ARGV are updated as described
in their descriptions above.
5. Function tracing is enabled: command substitu-
tion, shell functions, and subshells invoked with
( command ) inherit the DEBUG and RETURN traps.
6. Error tracing is enabled: command substitution,
shell functions, and subshells invoked with (
command ) inherit the ERROR trap.
extglob If set, the extended pattern matching features described
above under Pathname Expansion are enabled.
extquote
If set, $'string' and $"string" quoting is performed
within ${parameter} expansions enclosed in double
quotes. This option is enabled by default.
failglob
If set, patterns which fail to match filenames during
pathname expansion result in an expansion error.
force_fignore
If set, the suffixes specified by the FIGNORE shell
variable cause words to be ignored when performing word
completion even if the ignored words are the only possi-
ble completions. See SHELL VARIABLES above for a
description of FIGNORE. This option is enabled by
default.
globstar
If set, the pattern ** used in a pathname expansion con-
text will match a files and zero or more directories and
subdirectories. If the pattern is followed by a /, only
directories and subdirectories match.
gnu_errfmt
If set, shell error messages are written in the standard
GNU error message format.
histappend
If set, the history list is appended to the file named
by the value of the HISTFILE variable when the shell
exits, rather than overwriting the file.
histreedit
If set, and readline is being used, a user is given the
opportunity to re-edit a failed history substitution.
histverify
If set, and readline is being used, the results of his-
tory substitution are not immediately passed to the
shell parser. Instead, the resulting line is loaded
into the readline editing buffer, allowing further modi-
fication.
hostcomplete
If set, and readline is being used, bash will attempt to
perform hostname completion when a word containing a @
is being completed (see Completing under READLINE
above). This is enabled by default.
huponexit
If set, bash will send SIGHUP to all jobs when an inter-
active login shell exits.
interactive_comments
If set, allow a word beginning with # to cause that word
and all remaining characters on that line to be ignored
in an interactive shell (see COMMENTS above). This
option is enabled by default.
lithist If set, and the cmdhist option is enabled, multi-line
commands are saved to the history with embedded newlines
rather than using semicolon separators where possible.
login_shell
The shell sets this option if it is started as a login
shell (see INVOCATION above). The value may not be
changed.
mailwarn
If set, and a file that bash is checking for mail has
been accessed since the last time it was checked, the
message ‘‘The mail in mailfile has been read’’ is dis-
played.
no_empty_cmd_completion
If set, and readline is being used, bash will not
attempt to search the PATH for possible completions when
completion is attempted on an empty line.
nocaseglob
If set, bash matches filenames in a case-insensitive
fashion when performing pathname expansion (see Pathname
Expansion above).
nocasematch
If set, bash matches patterns in a case-insensitive
fashion when performing matching while executing case or
[[ conditional commands.
nullglob
If set, bash allows patterns which match no files (see
Pathname Expansion above) to expand to a null string,
rather than themselves.
progcomp
If set, the programmable completion facilities (see Pro-
grammable Completion above) are enabled. This option is
enabled by default.
promptvars
If set, prompt strings undergo parameter expansion, com-
mand substitution, arithmetic expansion, and quote
removal after being expanded as described in PROMPTING
above. This option is enabled by default.
restricted_shell
The shell sets this option if it is started in
restricted mode (see RESTRICTED SHELL below). The value
may not be changed. This is not reset when the startup
files are executed, allowing the startup files to dis-
cover whether or not a shell is restricted.
shift_verbose
If set, the shift builtin prints an error message when
the shift count exceeds the number of positional parame-
ters.
sourcepath
If set, the source (.) builtin uses the value of PATH to
find the directory containing the file supplied as an
argument. This option is enabled by default.
xpg_echo
If set, the echo builtin expands backslash-escape
sequences by default.
suspend [-f]
Suspend the execution of this shell until it receives a SIGCONT
signal. When the suspended shell is a background process, it can
be restarted by the fg command. For more information, read the
JOB CONTROL section. The suspend command can not suspend the
login shell. However, when -f option is specified, suspend com-
mand can suspend even login shell. The return status is 0
unless the shell is a login shell and -f is not supplied, or if
job control is not enabled.
test expr
[ expr ]
Return a status of 0 or 1 depending on the evaluation of the
conditional expression expr. Each operator and operand must be
a separate argument. Expressions are composed of the primaries
described above under CONDITIONAL EXPRESSIONS. test does not
accept any options, nor does it accept and ignore an argument of
-- as signifying the end of options.
Expressions may be combined using the following operators,
listed in decreasing order of precedence. The evaluation
depends on the number of arguments; see below.
! expr True if expr is false.
( expr )
Returns the value of expr. This may be used to override
the normal precedence of operators.
expr1 -a expr2
True if both expr1 and expr2 are true.
expr1 -o expr2
True if either expr1 or expr2 is true.
test and [ evaluate conditional expressions using a set of rules
based on the number of arguments.
0 arguments
The expression is false.
1 argument
The expression is true if and only if the argument is not
null.
2 arguments
If the first argument is !, the expression is true if and
only if the second argument is null. If the first argu-
ment is one of the unary conditional operators listed
above under CONDITIONAL EXPRESSIONS, the expression is
true if the unary test is true. If the first argument is
not a valid unary conditional operator, the expression is
false.
3 arguments
If the second argument is one of the binary conditional
operators listed above under CONDITIONAL EXPRESSIONS, the
result of the expression is the result of the binary test
using the first and third arguments as operands. The -a
and -o operators are considered binary operators when
there are three arguments. If the first argument is !,
the value is the negation of the two-argument test using
the second and third arguments. If the first argument is
exactly ( and the third argument is exactly ), the result
is the one-argument test of the second argument. Other-
wise, the expression is false.
4 arguments
If the first argument is !, the result is the negation of
the three-argument expression composed of the remaining
arguments. Otherwise, the expression is parsed and eval-
uated according to precedence using the rules listed
above.
5 or more arguments
The expression is parsed and evaluated according to
precedence using the rules listed above.
times Print the accumulated user and system times for the shell and
for processes run from the shell. The return status is 0.
trap [-lp] [[arg] sigspec ...]
The command arg is to be read and executed when the shell
receives signal(s) sigspec. If arg is absent (and there is a
single sigspec) or -, each specified signal is reset to its
original disposition (the value it had upon entrance to the
shell). If arg is the null string the signal specified by each
sigspec is ignored by the shell and by the commands it invokes.
If arg is not present and -p has been supplied, then the trap
commands associated with each sigspec are displayed. If no
arguments are supplied or if only -p is given, trap prints the
list of commands associated with each signal. The -l option
causes the shell to print a list of signal names and their cor-
responding numbers. Each sigspec is either a signal name
defined in , or a signal number. Signal names are
case insensitive and the SIG prefix is optional.
If a sigspec is EXIT (0) the command arg is executed on exit
from the shell. If a sigspec is DEBUG, the command arg is exe-
cuted before every simple command, for command, case command,
select command, every arithmetic for command, and before the
first command executes in a shell function (see SHELL GRAMMAR
above). Refer to the description of the extdebug option to the
shopt builtin for details of its effect on the DEBUG trap. If a
sigspec is RETURN, the command arg is executed each time a shell
function or a script executed with the . or source builtins fin-
ishes executing.
If a sigspec is ERR, the command arg is executed whenever a sim-
ple command has a non-zero exit status, subject to the following
conditions. The ERR trap is not executed if the failed command
is part of the command list immediately following a while or
until keyword, part of the test in an if statement, part of a
command executed in a && or ││ list, or if the command’s return
value is being inverted via !. These are the same conditions
obeyed by the errexit option.
Signals ignored upon entry to the shell cannot be trapped, reset
or listed. Trapped signals that are not being ignored are reset
to their original values in a subshell or subshell environment
when one is created. The return status is false if any sigspec
is invalid; otherwise trap returns true.
type [-aftpP] name [name ...]
With no options, indicate how each name would be interpreted if
used as a command name. If the -t option is used, type prints a
string which is one of alias, keyword, function, builtin, or
file if name is an alias, shell reserved word, function,
builtin, or disk file, respectively. If the name is not found,
then nothing is printed, and an exit status of false is
returned. If the -p option is used, type either returns the
name of the disk file that would be executed if name were speci-
fied as a command name, or nothing if ‘‘type -t name’’ would not
return file. The -P option forces a PATH search for each name,
even if ‘‘type -t name’’ would not return file. If a command is
hashed, -p and -P print the hashed value, not necessarily the
file that appears first in PATH. If the -a option is used, type
prints all of the places that contain an executable named name.
This includes aliases and functions, if and only if the -p
option is not also used. The table of hashed commands is not
consulted when using -a. The -f option suppresses shell func-
tion lookup, as with the command builtin. type returns true if
all of the arguments are found, false if any are not found.
ulimit [-HSTabcdefilmnpqrstuvx [limit]]
Provides control over the resources available to the shell and
to processes started by it, on systems that allow such control.
The -H and -S options specify that the hard or soft limit is set
for the given resource. A hard limit cannot be increased by a
non-root user once it is set; a soft limit may be increased up
to the value of the hard limit. If neither -H nor -S is speci-
fied, both the soft and hard limits are set. The value of limit
can be a number in the unit specified for the resource or one of
the special values hard, soft, or unlimited, which stand for the
current hard limit, the current soft limit, and no limit,
respectively. If limit is omitted, the current value of the
soft limit of the resource is printed, unless the -H option is
given. When more than one resource is specified, the limit name
and unit are printed before the value. Other options are inter-
preted as follows:
-a All current limits are reported
-b The maximum socket buffer size
-c The maximum size of core files created
-d The maximum size of a process’s data segment
-e The maximum scheduling priority ("nice")
-f The maximum size of files written by the shell and its
children
-i The maximum number of pending signals
-l The maximum size that may be locked into memory
-m The maximum resident set size (many systems do not honor
this limit)
-n The maximum number of open file descriptors (most systems
do not allow this value to be set)
-p The pipe size in 512-byte blocks (this may not be set)
-q The maximum number of bytes in POSIX message queues
-r The maximum real-time scheduling priority
-s The maximum stack size
-t The maximum amount of cpu time in seconds
-u The maximum number of processes available to a single
user
-v The maximum amount of virtual memory available to the
shell
-x The maximum number of file locks
-T The maximum number of threads
If limit is given, it is the new value of the specified resource
(the -a option is display only). If no option is given, then -f
is assumed. Values are in 1024-byte increments, except for -t,
which is in seconds, -p, which is in units of 512-byte blocks,
and -T, -b, -n, and -u, which are unscaled values. The return
status is 0 unless an invalid option or argument is supplied, or
an error occurs while setting a new limit. In POSIX Mode
512-byte blocks are used for the ‘-c’ and ‘-f’ options.
umask [-p] [-S] [mode]
The user file-creation mask is set to mode. If mode begins with
a digit, it is interpreted as an octal number; otherwise it is
interpreted as a symbolic mode mask similar to that accepted by
chmod(1). If mode is omitted, the current value of the mask is
printed. The -S option causes the mask to be printed in sym-
bolic form; the default output is an octal number. If the -p
option is supplied, and mode is omitted, the output is in a form
that may be reused as input. The return status is 0 if the mode
was successfully changed or if no mode argument was supplied,
and false otherwise.
unalias [-a] [name ...]
Remove each name from the list of defined aliases. If -a is
supplied, all alias definitions are removed. The return value
is true unless a supplied name is not a defined alias.
unset [-fv] [name ...]
For each name, remove the corresponding variable or function.
If no options are supplied, or the -v option is given, each name
refers to a shell variable. Read-only variables may not be
unset. If -f is specified, each name refers to a shell func-
tion, and the function definition is removed. Each unset vari-
able or function is removed from the environment passed to sub-
sequent commands. If any of COMP_WORDBREAKS, RANDOM, SECONDS,
LINENO, HISTCMD, FUNCNAME, GROUPS, or DIRSTACK are unset, they
lose their special properties, even if they are subsequently
reset. The exit status is true unless a name is readonly.
wait [n ...]
Wait for each specified process and return its termination sta-
tus. Each n may be a process ID or a job specification; if a
job spec is given, all processes in that job’s pipeline are
waited for. If n is not given, all currently active child pro-
cesses are waited for, and the return status is zero. If n
specifies a non-existent process or job, the return status is
127. Otherwise, the return status is the exit status of the
last process or job waited for.
RESTRICTED SHELL
If bash is started with the name rbash, or the -r option is supplied at
invocation, the shell becomes restricted. A restricted shell is used
to set up an environment more controlled than the standard shell. It
behaves identically to bash with the exception that the following are
disallowed or not performed:
· changing directories with cd
· setting or unsetting the values of SHELL, PATH, ENV, or BASH_ENV
· specifying command names containing /
· specifying a file name containing a / as an argument to the .
builtin command
· Specifying a filename containing a slash as an argument to the
-p option to the hash builtin command
· importing function definitions from the shell environment at
startup
· parsing the value of SHELLOPTS from the shell environment at
startup
· redirecting output using the >, >|, <>, >&, &>, and >> redirec-
tion operators
· using the exec builtin command to replace the shell with another
command
· adding or deleting builtin commands with the -f and -d options
to the enable builtin command
· Using the enable builtin command to enable disabled shell
builtins
· specifying the -p option to the command builtin command
· turning off restricted mode with set +r or set +o restricted.
These restrictions are enforced after any startup files are read.
When a command that is found to be a shell script is executed (see COM-
MAND EXECUTION above), rbash turns off any restrictions in the shell
spawned to execute the script.
SEE ALSO
Bash Reference Manual, Brian Fox and Chet Ramey
The Gnu Readline Library, Brian Fox and Chet Ramey
The Gnu History Library, Brian Fox and Chet Ramey
Portable Operating System Interface (POSIX) Part 2: Shell and Utili-
ties, IEEE
sh(1), ksh(1), csh(1)
emacs(1), vi(1)
readline(3)
FILES
/bin/bash
The bash executable
/etc/profile
The systemwide initialization file, executed for login shells
/etc/bash.bash_logout
The systemwide login shell cleanup file, executed when a login
shell exits
~/.bash_profile
The personal initialization file, executed for login shells
~/.bashrc
The individual per-interactive-shell startup file
~/.bash_logout
The individual login shell cleanup file, executed when a login
shell exits
~/.inputrc
Individual readline initialization file
AUTHORS
Brian Fox, Free Software Foundation
bfox@gnu.org
Chet Ramey, Case Western Reserve University
chet.ramey@case.edu
BUG REPORTS
If you find a bug in bash, you should report it. But first, you should
make sure that it really is a bug, and that it appears in the latest
version of bash. The latest version is always available from
ftp://ftp.gnu.org/pub/bash/.
Once you have determined that a bug actually exists, use the bashbug
command (from the source package) to submit a bug report. If you have
a fix, you are encouraged to mail that as well! Suggestions and
‘philosophical’ bug reports may be mailed to bug-bash@gnu.org or posted
to the Usenet newsgroup gnu.bash.bug.
ALL bug reports should include:
The version number of bash
The hardware and operating system
The compiler used to compile
A description of the bug behaviour
A short script or ‘recipe’ which exercises the bug
Comments and bug reports concerning this manual page should be directed
to chet@po.cwru.edu.
BUGS
It’s too big and too slow.
There are some subtle differences between bash and traditional versions
of sh, mostly because of the POSIX specification.
Aliases are confusing in some uses.
Shell builtin commands and functions are not stoppable/restartable.
Compound commands and command sequences of the form ‘a ; b ; c’ are not
handled gracefully when process suspension is attempted. When a pro-
cess is stopped, the shell immediately executes the next command in the
sequence. It suffices to place the sequence of commands between paren-
theses to force it into a subshell, which may be stopped as a unit.
Array variables may not (yet) be exported.
There may be only one active coprocess at a time.
GNU Bash-4.1 2009 December 29 BASH(1)