0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

標準出力、標準エラーのリダイレクトを理解する。

Last updated at Posted at 2024-11-19

検証

下記のファイルを用意する。
nonexistent_file.txt というファイルが以降で登場するが、これは存在しないファイルである。

existent_file.txt
Hello!! This is existing file.

リダイレクト元

(1)

1(標準出力) を stdout.txt に、2(標準エラー出力)を stderr.txt にリダイレクトする。
1(標準出力)は省略することができるので、1>stdout.txtではなくて、>stdout.txt のように書くこともできる。

$ (cat existent_file.txt && cat nonexistent_file.txt) 1>stdout.txt 2>stderr.txt
$
stdout.txt
Hello!! This is existing file.

stderr.txt
cat: nonexistent_file.txt: No such file or directory

(2)

&(標準出力と標準エラー出力) を stdout_stderr.txt に出力する。

$ (cat existent_file.txt && cat nonexistent_file.txt)  &>stdout_stderr.txt
$
stdout_stderr.txt
Hello!! This is existing file.
cat: nonexistent_file.txt: No such file or directory

リダイレクト先

(1)

1(標準出力) を &2(標準エラー出力) にリダイレクトして、2(標準エラー出力) を stderr.txt にリダイレクトします。

$ (cat existent_file.txt 1>&2) 2>stderr.txt
$ 
stderr.txt
Hello!! This is existing file.

(2)

2>&- によって、2(標準エラー出力) を破棄できます。

$ (cat existent_file.txt 1>&2) 2>&-
$

おまけ

terraform コマンドは、エラーでなくても、標準エラー出力にログが残るようである。
※ docker, terragrunt とか使ってますが、実質的にやっていることは、terraform validate です。

(1)

tee は、1(標準出力)をファイルに保存しつつ、元の出力も維持するコマンドです。
下記を見ると、debug_output.txt ファイルに何も表示されてないので、terraform コマンドは、標準出力ではなくて、標準エラー出力にログを出しているみたい。

$ docker exec terraformmy-tfcontainer-1 sh -c "(cd envs/dev && terragrunt validate)" | tee debug_output.txt
16:55:27.017 STDOUT terraform: Success! The configuration is valid.
16:55:27.017 STDOUT terraform: 
$
debug_output.txt

(2)

下記のように、2(標準エラー出力) を &1(標準出力) にリダイレクトすることで、teeでファイルに保存することができる。

$ docker exec terraformmy-tfcontainer-1 sh -c "(cd envs/dev && terragrunt validate)" 2>&1 | tee debug_output.txt
16:57:03.589 STDOUT terraform: Success! The configuration is valid.
16:57:03.589 STDOUT terraform: 
$
debug_output.txt
[0;90m16:57:03.589 [0m[0;37mSTDOUT [0m[0;36mterraform: [0m[32m[1mSuccess![0m The configuration is valid.[0m
[0;90m16:57:03.589 [0m[0;37mSTDOUT [0m[0;36mterraform: [0m[0m[0m

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?