シェルスクリプトの中でヒアドキュメントを使う場合、

#!/bin/sh

cat << EOF
	hoge
	fuga
EOF

と書いて、これを実行すると

	hoge
	fuga

という出力となる。

ヒアドキュメントでは識別文字(この例ではEOF)から識別文字までの間を「忠実に」出力するわけなので、この出力で正しい。

このため、実行結果には反映させたくなくとも、スクリプト内の「見やすさ」のためにヒアドキュメント内で空白文字を使うと、予期せぬ(この場合は忠実であることが人間にとって予期せぬ=期待しないというだけだが)こととなる。

ヒアドキュメントとはそういうものだ、と長らく思っていたが、実は実に簡単な方法での解決方法があった。

以下の通り実行する。

#!/bin/sh

cat <<- EOF
	hoge
	fuga
EOF

赤色文字の「-」を追加しただけだが、たったのこれだけで

hoge
fuga

前述の例のように先頭に空白文字は含まれず、このように都合のいい出力となる。
sh(1)によると

Here Documents
       This  type  of  redirection  instructs the shell to read input from the
       current source until a line containing  only  word  (with  no  trailing
       blanks)	is seen.  All of the lines read up to that point are then used
       as the standard input for a command.

       The format of here-documents is:

	      <<[-]word
		      here-document
	      delimiter

       No parameter expansion, command substitution, arithmetic expansion,  or
       pathname expansion is performed on word.  If any characters in word are
       quoted, the delimiter is the result of quote removal on word,  and  the
       lines  in the here-document are not expanded.  If word is unquoted, all
       lines of the here-document are subjected to parameter  expansion,  com-
       mand  substitution,  and arithmetic expansion.  In the latter case, the
       character sequence \<newline> is ignored, and \ must be used  to  quote
       the characters \, $, and `.

       If the redirection operator is <<-, then all leading tab characters are
       stripped from input lines and  the  line  containing  delimiter.   This
       allows  here-documents within shell scripts to be indented in a natural
       fashion.

とあるようにリダイレクトが「<<-」である場合はそれぞれの行の行頭にあるタブは全て取り除かれる、とある。
試してみたところ、タブが複数あっても全て取り除かれる、またタブではなく空白文字(スペース)ではNG(取り除かれない)であった。

以上の内容をBシェル触りだして10年ほど経つ今日初めて知った。(恥)

このエントリは 2009年1月16日 02:03:14に投稿されました。 unixの下にカテゴリされています。 RSS 2.0フィードを通してこのエントリのコメントをフォローすることが出来ます。 コメントするか、あなた自身のサイトからトラックバック出来ます。

add to hatena hatena.comment (2) add to del.icio.us (0) add to livedoor.clip (0) add to Yahoo!Bookmark (0) Total: 2

コメントする?