LoginSignup
19

More than 3 years have passed since last update.

【Linux】echoコマンドの使用方法

Posted at

はじめ

Linuxコマンドの一つのechoコマンドについて、自分がよく使用している方法をアウトプットします。
※全ての使用方法は網羅できておりませんので、ご了承下さい。

echoコマンドとは?

このようなことができるコマンドになります。

  • 画面に文字列の表示
  • コマンドの実行結果の表示
  • 文字列をファイルに出力
  • 文字列をファイルに追記

echoコマンドの使用方法(例)

文字列の表示

指定の文字列を表示します。

コマンド
echo "文字列"

コマンド実行例

実行例
[root@tspweb01 test]# echo aaaaa
aaaaa

コマンドの実行結果の表示

コマンドの実行結果を表示します。

コマンド
echo $?
  • コマンドの実行結果
実行結果 内容
0 True(コマンドの実行が成功)
1 False(コマンドの実行が失敗)
127 コマンドが見つからない

コマンド実行例

  • True(成功)
実行例(True)
[root@tspweb01 test]# true
[root@tspweb01 test]# echo $?
0
  • False(失敗)
実行例(False)
[root@tspweb01 test]# false
[root@tspweb01 test]# echo $?
1
  • コマンドが見つからない
実行例(コマンドが見つからない)
[root@tspweb01 test]# wh
-bash: wh: コマンドが見つかりません
[root@tspweb01 test]# echo $?
127
[root@tspweb01 test]#

文字列をファイルに出力

指定の文字列をファイルに出力します。

コマンド
echo "文字列" > ファイル名

コマンド実行例

実行例
[root@tspweb01 test]# echo "testtest" > test.txt
[root@tspweb01 test]# cat test.txt
testtest
[root@tspweb01 test]#

文字列をファイルに追記

指定の文字列をファイルに追記します。

コマンド
echo "文字列" >> ファイル名

コマンド実行例

[root@tspweb01 test]# cat test.txt
testtest
[root@tspweb01 test]# echo "testtest" >> test.txt
[root@tspweb01 test]#
[root@tspweb01 test]# cat test.txt
testtest
testtest
[root@tspweb01 test]#

注意

実作業の際には、>>>を間違えないようにお気をつけ下さい。
(意味が全然違います。)

  • > : ファイル全体の上書き
  • >> : ファイルの最終行に1文を追記

重要なファイルの作業を実施する際は、必ずcpコマンドにてバックアップを取得しましょう。

まとめ

echoコマンドでは、このようなことができます。

  • 画面に文字列の表示
  • コマンドの実行結果の表示
  • 文字列をファイルに出力
  • 文字列をファイルに追記

bashスクリプトに応用してみては、如何でしょうか?

参考

echoコマンドの詳細まとめました【Linuxコマンド集】
意外と便利なコマンドtrue/false

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
19