2020-11-04に更新

【Linux】teeコマンド

Linuxの標準出力をファイルに保存する時にリダイレクトがよく使われます。
しかしながら、仕組み上ターミナル画面には何も出なくなるため、
画面の出力も同時に見たい場面では困ります。
そのような場面で活躍するのが、標準出力しつつ、ファイルへ保存も可能な「tee」コマンドです。

例) リダイレクトの場合

$ yum check-update bash > update-redirect.log
$ cat update-redirect.log
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd

bash.x86_64                      4.2.46-33.amzn2                      amzn2-core

yum check-update bashの出力が画面がファイルへ保存されるが、ターミナルには出力されない

例) teeコマンドの場合

$ yum check-update bash | tee update-tee.log
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd

bash.x86_64                      4.2.46-33.amzn2                      amzn2-core
$ cat update-tee.log
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd

bash.x86_64                      4.2.46-33.amzn2                      amzn2-core

yum check-update bashの出力画面がターミナルに出ている&ファイルにも保存されている

teeの便利な使い方

リダイレクト先に書き込むときにrootの権限が必要なファイルへ出力する場合にも使えます

例)リダイレクトで書き込み不可

$ echo 'Hello World' > /var/www/html/index.html
-bash: /var/www/html/index.html: Permission denied

権限が足りない

例)リダイレクトで書き込み不可2

$ sudo echo 'Hello World' > /var/www/html/index.html
-bash: /var/www/html/index.html: Permission denied

もちろんこれも権限が足りない

例)sudo teeで書き込みする

$ echo 'Hello World' | sudo tee /var/www/html/index.html
Hello World
$ cat /var/www/html/index.html
Hello World

書き込みできました!

ツイッターでシェア
みんなに共有、忘れないようにメモ

arohajiro

しがない元インフラエンジニアです

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント