LoginSignup
4
6

More than 5 years have passed since last update.

いつかどこかで役に立つechoについて

Last updated at Posted at 2016-11-25

はじめに

echoコマンドについて調べたので備忘録がてらここに記しておく。対象はGNU版echoである。BSD版、及びSystem V版echoは試していない。

ちなみに、echoコマンドとは、与えられた文字列を標準出力に書き出すためのコマンドである。ほぼすべてのshellに組み込みコマンドとして入っているが、挙動は全く同一というわけではないので十分注意が必要なコマンドのひとつである。

シンタックス

シンタックスはこの通り。

echo [SHORT-OPTION]... [STRING]...

echoコマンドのオプション

Options Description
-n 行末の改行をしない
-e バックスラッシュでエスケープされた文字の解釈を有効にする
\\ バックスラッシュ
\a アラート
\b バックスペース
\n 改行
\r 復帰
\t 水平タブ
\v 垂直タブ
\c 行末の改行をしない

次章からは、各オプションを使ったときの挙動について記す。

13個のechoコマンド出力例

1. 入力と出力

文字列の入力と標準出力を行う。

$ echo You are the Laughing Man, aren’t you?
You are the Laughing Man, aren’t you?

2. 変数

変数を定義し、その値をechoで出力する。

$ i=3
$ echo This is the "$i"rd time that we’ve met, yet you know who I am? Although they just call me that.
This is the 3rd time that we’ve met, yet you know who I am? Although they just call me that.

3. -e\aオプション

アラートを発生させる。

$ echo -e "It’s quite audacious of you to come here. Why did you come \ahere?"
It’s quite audacious of you to come here. Why did you come here?

ボリュームの音量に注意しましょう。

4. -e\bオプション

すべてのスペースを取り除く。

$ echo -e "I \bcame \bhere \bto \bbe \bsaved \bby \byou."
Icameheretobesavedbyyou.

5. -e\nオプション

各単語の間に改行を挿入する。

$ echo -e "Don’t \nyou \nmean \nthe \nother \nway \naround?"
Don’t
you
mean
the
other
way
around?

6. -e\rオプション

キャリッジリターンを挿入して改行する。

$ echo -e "True. But I’m so beat up right now that \rthis is the only method I can think of."
this is the only method I can think of.

7. -e\tオプション

水平タブを挿入する。

$ echo -e "How \tselfish \tof \tyou."
How     selfish         of      you.

8. -e\vオプション

垂直タブを挿入する。

$ echo -e "I \vcan’t \vafford \vto \vlose \vany \vmore \vtime."
I
  can’t
        afford
               to
                  lose
                       any
                           more
                                time.

9. -e\cオプション

改行させないようにする。

$ echo -e "Well then, \cwhat would the Net’s hero want me to do?"
Well then, $

10. -nオプション

改行させないようにする。

$ echo -n "I am going to tell you the truth behind the Laughing Man case."
I am going to tell you the truth behind the Laughing Man case.$

11. lsコマンド その1

lsコマンドの代替として使う。

$ echo *
of.txt psychoanalyst.txt Stekel.md the.txt Wilhelm.md Words.txt

12. lsコマンド その2

特定の種類のファイルのみ出力する。

$ echo *.md
Stekel.md Wilhelm.md

13. リダイレクト

リダイレクトしてファイルに文字列を書き出す。

$ echo "I will leave my memories behind. I am counting on you." > CAPTIVATED
$ cat CAPTIVATED
I will leave my memories behind. I am counting on you.

出典

欧州版 攻殻機動隊SAC Episode 19 "偽装網に抱かれて CAPTIVATED" より

4
6
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
4
6