为什么我的here-docs(<< - )给我一个语法错误?

Ank*_*oel 3 bash operators

methods() {
        cat <<-!
        start
        stop
        restart
        reload
        status
        methods
        !
}
Run Code Online (Sandbox Code Playgroud)

这是正确的我得到错误

syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 6

对于古代shell中的here-docs,您必须完全匹配标记.这意味着:

methods() {
        cat <<!
        start
        stop
        restart
        reload
        status
        methods
!
}
Run Code Online (Sandbox Code Playgroud)

是的,在该行的开头,虽然你可以做一些棘手的事情,比如cat <<'^I!'将标记设置为单个标签,然后是!.

现在bash(可能还有早期的shell)修复了<<-变量,它在处理之前剥离了数据行和结束标记的所有前导标签.这样,你仍然可以很好地缩进:

methods() {
        cat <<-!
        start
        stop
        restart
        reload
        status
        methods
        !
}
Run Code Online (Sandbox Code Playgroud)

但是,请注意附带条件:它会剥离制表符,而不是一般的空格.如果在该字符之前的任何位置有空格(或任何非制表符,可打印或其他)!,则它将不起作用.

如果您正在使用vi,则可以输入:set list以更好地查看不可打印的字符,否则xd或者od -xcb可以为您提供文件的十六进制转储.