Section Next | Prev


3.3.1 入出力リディレクション機能

UNIX では、各プロセス(コマンド実行)に際して次の3つの入出力装置を 自動的に割り当てます。
ファイルID 意味
標準入力(stdin)。キーボード
標準出力(stdout)。ディスプレイ
診断(エラー)出力(stderr)。ディスプレイ

通常これらは端末を割り当てているため端末(キーボード)から入力し、 端末(ディスプレイ)に出力を行い、エラー・メッセージも端末に出力します。
シェルは、これら3つの入出力をファイルに切り換える事でき、 入出力リダイレクション(redirection) と言います。

出力のリダイレクション
次の様することで ls コマンドの出力を test.out ファイルへできます。
	[student@h006 dir1]$ ls -l > test.out
	[student@h006 dir1]$ cat test.out
	合計 16
	-rw-rw-r-- 1 student student   8  7月 22 10:13 a.dat
	-rw-r--r-- 1 student student  43  7月 22 10:09 name.data
	-rw-rw-r-- 1 student student  43  7月 22 10:09 name.list
	-rw-rw-r-- 1 student student   0  7月 22 12:56 test.out
	-rw-rw-r-- 1 student student 567  7月 22 10:09 versions.txt
となります。
すでに存在しているファイルに付け加える時は2重の負等号「大なり」 ( >> )を使用します。
	# 追加書込の例
	[student@h006 dir1] ls -l >> test.out

標準出力とエラー出力の扱い
ファイルIDを明示して、エラー出力と標準出力を別々に扱うこともできます。
エラーメッセージは stdout へ、それ以外は stdout に表示される。
	[student@h006 ~]$ ls /etc/hosts /datarame
	ls: /detarame: そのようなファイルやディレクトリはありません
	/etc/hosts
普通の出力リダイレクションは stdout のみ切替える。
( stderr が残ってしまう )
	[student@h006 ~]$ ls /etc/hosts /detarame > /dev/null
	ls: /detarame にアクセスできません: そのようなファイルやディレクトリはありません
エラーメッセージ(stderr=2)をリダイレクションするにはファイルIDを指定。
( この場合は標準出力が残ってしまう )
	[student@h006 ~]$ ls /etc/hosts /detarame 2> /dev/null
	/etc/hosts
両方をまとめる場合には「大なり」(>)にアンド(&)を続けて指定します。
まずどの出力をリダイレクションするかを指定し、
続けてどのようにまとめる(合流させるか)を指定する。
	[student@h006 ~]$ ls /etc/hosts /detarame > /dev/null 2>&1
	上記の場合、stderr(2)をstdout(1)へ連結している。

	よって、2と1の表示順によって動作が変わることに注意。
	[student@h006 ~]$ ls /etc/hosts /detarame > /dev/null 1>&2
	ls: /detarame: そのようなファイルやディレクトリはありません
	/etc/hosts

入力のリダイレクション
入力をキーボードからファイルに切り換えるには負等号「小なり」 ( < )を使用します。
	[student@h006 ~]$ wc < test.out
		22	 166	  1368
さらに、ファイルではなくキーボードからの入力を書き溜めておき、 一気にコマンドに入力する方法もあります。
	[student@h006 ~]$ wc << EOD
	> Hello, world.
	> Here document sample
	> EOD
	      2       5      36
これはヒアドキュメントとよばれ、2重の小なり( << )と、 それに続けてデータの終わりを表すキーワードを記述します。
開始するとシェルの継続行プロンプト(PS2で定めた値)が表示され、 終了キーワードを入力するまで継続されます。

補足)リダイレクション上書きの禁止
ファイルリダイレクションにより、ファイル上書きしないようシェルオプションを指定する事ができます。
	[student@h006 ~]$ date > a
	[student@h006 ~]$ date >> a

	[student@h006 ~]$ set -o noclobber
	[student@h006 ~]$ date > a 	# 上書きはできない
	-bash: date.out: 存在するファイルを上書きできません
	[student@h006 ~]$ date >> a	# 追加は可能

Section Next | Prev

Copyright 2007-2018 ycosSystems Shell/Body331.html