0
1

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 1 year has passed since last update.

echoとcatの役割って理解してる?

今回,卒業研究のシェルスクリプトを作成した.スクリプトの書き方を調べる過程で,サイトによってファイルに書き込みを行う処理をechoコマンドとcatコマンドのどちらを使用するかばらつきがあった.ここでそもそも自分自身がこれらのコマンドの違いを理解できていない事に気づいたため,本投稿にまとめる.

先に結論

スクリプトのファイル書き込み処理を書く場合は,どちらでも良い.

各コマンドの根本的な違い

catコマンド

ファイルや標準入力装置のデータを取得し,そのデータを標準出力装置に表示する.

echoコマンド

文字列を画面に表示する.

ファイル書き込みの書き方の違い

catコマンド

書き込み先のファイルを先に指定し,書き込む内容をEOFで囲む.

# ファイルに上書きする場合
cat > cat_text.txt <<EOF
Line 1
Line 2
EOF

# ファイルに追記する場合
cat >> cat_text.txt <<EOF
Additional line
EOF

echoコマンド

書き込み先のファイルを後に指定し,書き込む内容をダブルクォーテーションで囲む.

# ファイルに上書きする場合
echo "sample text" > echo_text.txt

# ファイルに追記する場合
echo "Additional text" >> echo_text.txt

※echoコマンドは一行ずつの書き込みしかできないという情報があるが,実際には複数行でも問題なく書き込める.

結論

  • 書き方の違いがあるが,できることに違いはない.
  • 視認性や好みで選んでよい.
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?