エラー出力のリダイレクト
Linux では、コマンドは 2 種類の出力を生成します。
- 標準出力 (standard output, stdout) - コマンドの通常の出力
- 標準エラー (standard error, stderr) - コマンドによって生成されるエラーメッセージ
これまでは標準出力のリダイレクトについて学んできました。では、標準エラーのリダイレクトの方法を学んでみましょう。
標準エラーはファイルディスクリプタ 2 を使用するため、これをリダイレクトするには 2>
を使用します。存在しないファイルを一覧表示して、エラーを生成してみましょう。
ls non_existent_file.txt
エラーメッセージが表示されます。
ls: cannot access 'non_existent_file.txt': No such file or directory
では、このエラーメッセージをファイルにリダイレクトしましょう。
ls non_existent_file.txt 2> error.log
今回は、エラーメッセージが error.log
ファイルにリダイレクトされているため、画面にはエラーメッセージが表示されません。このファイルの内容を確認してみましょう。
cat error.log
出力:
ls: cannot access 'non_existent_file.txt': No such file or directory
また、標準出力と標準エラーをそれぞれ異なるファイルにリダイレクトすることもできます。
## 正常に一覧表示できるファイルを作成する
echo "This is a test file" > existing_file.txt
## stdout を1つのファイルに、stderr を別のファイルにリダイレクトする
ls existing_file.txt non_existent_file.txt > output.log 2> error2.log
## 両方のファイルを確認する
echo "Content of output.log:"
cat output.log
echo "Content of error2.log:"
cat error2.log
出力:
Content of output.log:
existing_file.txt
Content of error2.log:
ls: cannot access 'non_existent_file.txt': No such file or directory
&>
を使用すると、標準出力と標準エラーを同じファイルにリダイレクトすることもできます。
ls existing_file.txt non_existent_file.txt &> combined.log
cat combined.log
これにより、通常の出力とエラーメッセージの両方が combined.log
ファイルに記録されます。