且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Bash脚本:语法错误:文件意外结束

更新时间:2022-02-26 22:50:24

这里的文档是棘手的野兽.如果您使用'EOF'恰好是 结束线,那么前面没有空格.

Heredocs are tricky beasts to get right. If you use 'EOF' that's exactly what the closing line needs to be, with no whitespace at the front like you have.

或者,您可以使用<<-变体,该变体从heredoc 的结束行中剥离所有前导制表符,如下成绩单(其中< tab> TAB 字符):

Alternatively, you can use the <<- variant which strips off all leading tab characters from the lines in the heredoc and the closing line as per the following transcript (where <tab> is the TAB character):

pax> cat <<-'eof'
...> 1
...< 2
...> <tab>eof
...> 4
...> eof

1
2
<tab>eof
4

pax> cat <<-'eof'
...> 1
...> 2
...> <tab>eof

1
2

使用<<-变体可以使文件更整洁,但是如果要保留开头的标签,那当然不好.在 bash 联机帮助页中:

Using the <<- variant allows for neater files, thoug it's no good if you want to preserve leading tabs of course. From the bash manpage:

如果重定向运算符是<<-,则所有前导制表符从输入行和包含定界符的行中除去.这样就可以自然地缩进shell脚本中的here-document.

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.

当然,如果您只是想将这些文件用作标记文件,则使用带有Heredoc的方法比 cat 更好.只需使用:

Of course, if you're just wanting to use those files as flag files, there's a better way than cat with a heredoc. Just use:

touch "$basedirectory$FEATURE_EXT.$SENT_EXT"

这将创建文件(如果文件不存在),并更新文件的修改时间,就像 cat 一样,但不会弄乱heredocs.它不会清空文件,但是,如果出于某些原因需要该文件:

This will create the file if it doesn't exist and update the modification time if it does, just like the cat but without messing about with heredocs. It won't empty the file but, if you need that for some reason:

rm -f "$basedirectory$FEATURE_EXT.$SENT_EXT"
touch "$basedirectory$FEATURE_EXT.$SENT_EXT"

可以解决问题.

但是,由于Heredoc实际上确实输出了一个空行(一个 \ n 字符),因此您可以选择:

However, since the heredoc does actually output a single empty line (one \n character), you can opt for:

echo >"$basedirectory$FEATURE_EXT.$SENT_EXT"

相反.