ども、シローです。
今回はリダイレクトについて整理していきたいと思います。
リダイレクトをうまく使うことで、コマンドの出力をファイルにコピーしたり、ファイルから読み取った内容をコマンドに渡すことができます。
リダイレクトの記号一覧
記号 | 内容 |
< file | 標準入力をfileに変更する |
> file | 標準出力をfileに変更する |
>> file | 標準出力の末尾に追加する |
>| file | noclobberの設定を無視して標準出力をfileに変更する |
2> file | 標準エラー出力をfileに変更する |
2>> file | 標準エラー出力をfileの末尾に変更する |
2>| file | noclobberの設定を無視して標準エラーをfileに変更する |
>&m | 標準出力をファイルディスクリプタm番にコピーする |
n>&m | ファイルディスクリプタn番をファイルディスクリプタm番にコピーする |
標準入出力について
コマンドを実行するための入力元や実行後の出力先
名前 | 内容 |
標準入力(stdin) | 標準的な入力元。通常はキーボード |
標準出力(stdout) | 標準的な出力先。通常は端末ディスプレイ |
標準エラー出力(stderr) | 標準的なエラー出力先。通常は端末ディスプレイ |
標準入出力とファイルディスクリプタの番号
コマンドをリダイレクトするときの、標準入出力に対応するのがファイルディスクリプタの番号
名前 | ファイルディスクリプタの番号 |
標準入力 | 0 |
標準出力 | 1 |
標準エラー出力 | 2 |
noclobberとは
標準出力先のファイルがすでに存在して、内容が記述されているときに上書きして元の内容が消えてしまうのを防ぐオプション
set -o noclobber
を打つと既に記述されているファイルの上書きはできなくなる
set + noclobber
と打つとnoclobberが解除される
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$ cat result.txt /usr: bin games include lib local sbin share src $ set -o noclobber $ echo test > result.txt bash: result.txt: cannot overwrite existing file $ set +o noclobber |
色んな例
出力した内容をファイルに記述する
1 2 3 4 5 6 7 8 9 10 |
$ ls /usr > result.txt $ cat result.txt bin games include lib local sbin share src |
result.txtにls /usr
した結果が格納される
エラー出力を標準出力を別々のファイルに分けて記述する
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$ ls /usr /xxx > result.txt 2> error.txt $ cat result.txt /usr: bin games include lib local sbin share src $ cat error.txt ls: cannot access '/xxx': No such file or directory |
標準出力内容をファイルの末尾に追記する
1 2 3 4 5 6 7 |
$ echo hoge >> echo_result.txt $ echo fuga >> echo_result.txt $ echo piyo >> echo_result.txt $ cat echo_result.txt hoge fuga piyo |
標準出力と標準エラー出力を同じファイルに記述する
1 2 3 4 5 6 7 8 9 10 11 12 |
$ ls /usr /xxx > result.txt 2>&1 $ cat result.txt ls: cannot access '/xxx': No such file or directory /usr: bin games include lib local sbin share src |
※リダイレクトの位置を間違えると失敗する
1 2 3 4 5 6 7 8 9 10 11 12 |
$ ls /usr /xxx 2>&1 > result.txt ls: cannot access '/xxx': No such file or directory $ cat result.txt /usr: bin games include lib local sbin share src |
※&>
を使うと標準出力とエラー出力を一緒にまとめてファイルに記述できる
1 2 3 4 5 6 7 8 9 10 11 12 |
$ ls /usr /xxx &> result.txt $ cat result.txt ls: cannot access '/xxx': No such file or directory /usr: bin games include lib local sbin share src |
エラー出力を無視する
1 2 3 |
$ ls /usr /xxx 2> /dev/null /usr: bin games include lib local sbin share src |
2>
でエラー出力先を指定して、その場所を/dev/null
という入れたものを全て無にするところにするとエラー内容を無視して標準出力だけが表示される。
ファイルから読み取ったテキストを標準入力にしてコマンドを実行
1 2 3 |
$ echo abcd > word.txt $ tr b B < word.txt aBcd |
tr
コマンドで受け取る入力値をword.txtの内容に設定している。
※標準入力と標準出力に同じファイルを指定すると、そのファイルが空になるのは注意
1 2 |
$ tr b B < word.txt > word.txt $ cat word.txt |
これは標準出力先に指定した時点でそのファイルが空になって、その内容を標準入力で読み取って、結果(もちろん空)をファイルに記述しているからです。
まとめ
- リダイレクトを使うと、コマンドの入力や出力をテキストファイルに設定できる
- 重要なファイルへの上書きを避けるためには、noclobberオプションがある
- 標準エラー出力を、標準出力を一緒にするためには
2>&1 file
、あるいは&> file
- 標準エラーのみを別ファイルに出力したい場合は
2> file