LoginSignup
95
87

More than 5 years have passed since last update.

bash:標準出力も標準エラーもログに出力

Last updated at Posted at 2015-05-24

障害対応時などの一刻を争う調査などの際、この挙動にハマってしまって対応が遅れるケースを見てきたんで共有です。

test.sh

sonna_file_naiyo.txtが存在しないとして

#!/bin/sh

echo "foo"
cat ./sonna_file_naiyo.txt
echo "bar"

で、このスクリプトを

teeでロギングしちゃうよ!

$ sh ./test.sh | tee test.log
foo
cat: ./sonna_file_naiyo.txt: No such file or directory
bar

logの中身を見てみるよ!

$ cat ./test.log 
foo
bar

(´・ω・`) 標準エラー出力がファイルに吐かれてないお・・・なぜだお・・・

標準出力&標準エラーどちらもロギングする場合

標準エラー出力を標準出力にリダイレクトする方法を検討しましょ

$ sh ./test.sh 2>&1 | tee test.log
foo
cat: ./sonna_file_naiyo.txt: No such file or directory
bar

確認するよ!

$ cat ./test.log 
foo
cat: ./sonna_file_naiyo.txt: No such file or directory
bar

(∩´∀`)∩ワーイ

teeではなくファイルへのリダイレクトを使う場合

>>>でファイルへ出力するケースもあると思います。

その際にも同様にリダイレクトを行いますが、どこに記述するかについて慎重になるべきです

$ sh ./test.sh > test.log 2>&1

$ cat test.log 
foo
cat: ./sonna_file_naiyo.txt: No such file or directory
bar

上記は想定通りの挙動例

指定の順番や位置を間違えると

意図しない状況になりますので注意です

$ sh ./test.sh | tee test.log 2>&1
foo
cat: ./sonna_file_naiyo.txt: No such file or directory
bar

$ cat test.log 
foo
bar
$ sh ./test.sh 2>&1 > test.log
cat: ./sonna_file_naiyo.txt: No such file or directory

$ cat test.log 
foo
bar

(´・ω・`)結構ハマりやすいと思うので、注意したいですね(自戒)

95
87
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
95
87