14
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Shell】変数への格納と標準出力を同時に行う方法

Posted at

はじめに

以下のような変数への格納と標準出力を、同時に行う方法を調べてみました。

$ var=hello
$ echo $var
hello

結論

teeコマンドと、端末/dev/ttyを使用します。

$ var=$(echo "hello" | tee /dev/tty)
hello
$ echo $var
hello

詳細

tee

teeコマンドは、リダイレクトされた内容を、引数のファイルや変数にコピーするコマンドです。

# helloを hello.txt にコピー
$ echo  "hello" | tee hello.txt
hello
$ cat hello.txt
hello

tee(T)という名前は、このスキームに由来するそうです (下図がTのように見えることから)

Tee

引用: https://en.wikipedia.org/wiki/Tee_(command)

/dev/tty

/dev/ttyは現在のプロセスの制御端末を指します。
そのため、/dev/ttyになにかを入力すると、現在の端末に出力されます。

$ echo 1 > /dev/tty
1

この 2 つを合わせることで、変数への格納と標準出力を同時に行います。

$ echo "hello" | tee /dev/tty
hello # echo "hello" の出力結果
hello # tee で /dev/tty にコピーされ、現在の端末に出力されたもの
# echo "hello" の出力結果が、$var に格納される
$ var=$(echo "hello" | tee /dev/tty)
hello # tee で /dev/tty にコピーされ、現在の端末に出力されたものは、変化なし

参考

14
5
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
14
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?