3
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 5 years have passed since last update.

ヒアドキュメントでparse error near `\n'というエラーが出た時の対応方法

Posted at

『crontab -e(crontabの削除)』を実行する前にバックアップもかねて、crontabの内容を標準出力させるようにしました。

実行結果↓

$ crontab -r

-----
# hoge
----- 

当初、以下のようなメソッドを用意しました。

function crontab () {
	if [ "$1" = "-r" ]; then
		cat <<EOF
		-----
		`crontab -l`
		-----
		EOF
		command crontab -r;
	else
		command crontab "$@";
	fi
}

しかし、以下のようなエラーが出ました。

parse error near `\n'

原因と解決方法

ヒアドキュメントを書く際、『EOF』は行頭にないといけないらしいです。

以下の場合ですとエラーは出ません。

function crontab () {
	if [ "$1" = "-r" ]; then
		cat <<EOF
		-----
		`crontab -l`
		-----
-		EOF
# 行頭にEOFを書くとエラーが解決する
+EOF
		command crontab -r;
	else
		command crontab "$@";
	fi
}

もしくは、以下のようにハイフンをつけてあげると解決します。

function crontab () {
	if [ "$1" = "-r" ]; then
-		cat <<EOF
+		cat <<-EOF
		-----
		`crontab -l`
		-----
		EOF
		command crontab -r;
	else
		command crontab "$@";
	fi
}

さいごに

まだシェルスクリプトの挙動についてしっかりと理解できていないのですが、同じようなエラーに遭遇している人の参考になればさいわいです。

3
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
3
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?