LoginSignup
9
5

More than 1 year has passed since last update.

ヒアドキュメント とは

Posted at

勉強前イメージ

cat的なやつイメージ?

調査

ヒアドキュメント とは

ヒア文字列とも言われます。
プログラミング言語の機能の一つで、改行コードなど特殊な文字列をソースコードの中に記述するための方法です。
言語によって記法は異なりますがよく使われるヒアドキュメントの開始など型は決まっています。

なぜヒアドキュメントを使うかというと、以下ヒアドキュメントを使う場合と使わない場合のシェルスクリプトを置いてみましたが
可読性も高まり修正もしやすくなります。

  • ヒアドキュメントを使わない場合
#!/bin/bash
echo "hello world!"
echo "hello world!!"
echo "hello world!!!"
echo "hello world!!!!"
echo "hello world!!!!!"
  • ヒアドキュメントを使う場合
!/bin/bash
cat <<EOF
hello world!
hello world!!
hello world!!!
hello world!!!!
hello world!!!!!
EOF

ヒアドキュメントの書き方

  • 通常

通常の記載方法は上記にも記載していますが cat <<EOFEOF で表示したい文章をはさみます。

!/bin/bash
cat <<EOF
[文字列]
....
[文字列]
EOF
  • 変数

以下のように変数展開も可能です。

#!/bin/bash
STR="Hello world"

cat <<EOF
${STR}
hello world!
hello world!!
EOF
  • 変数展開しない

変数と認識される文字列をそのまま文字列で表示させるにはEOFにダブルクォーテーションをつけることで展開されないようにできます。

#!/bin/bash
STR="Hello world"

cat <<"EOF"
${STR}
hello world!
hello world!!
EOF
  • コマンド実行

以下のようにバッククォートで囲むことでコマンドも実行されます。

#!/bin/bash

cat <<EOF
hello world!
hello world!!
`date`
EOF
  • コマンド実行しない

変数同様EOFにダブルクォーテーションをつけることで中身のコマンドが実行されません。

#!/bin/bash

cat <<"EOF"
hello world!
hello world!!
`date`
EOF

勉強後イメージ

ヒアドキュメントという言葉はほぼ知らなかったけど使ったことはあったわ。
ただ、そんなややこしいことはしてなかったので
変数展開できるとかコマンド実行できるとかは知らなかった。

参考

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