here-document gives 'unexpected end of file' error

后端 未结 7 2447
生来不讨喜
生来不讨喜 2020-11-22 04:42

I need my script to send an email from terminal. Based on what I\'ve seen here and many other places online, I formatted it like this:



        
7条回答
  •  长情又很酷
    2020-11-22 05:30

    When I want to have docstrings for my bash functions, I use a solution similar to the suggestion of user12205 in a duplicate of this question.

    See how I define USAGE for a solution that:

    • auto-formats well for me in my IDE of choice (sublime)
    • is multi-line
    • can use spaces or tabs as indentation
    • preserves indentations within the comment.
    function foo {
        # Docstring
        read -r -d '' USAGE <<'    END'
            # This method prints foo to the terminal.
            #
            # Enter `foo -h` to see the docstring.
            #      It has indentations and multiple lines.
            #
            # Change the delimiter if you need hashtag for some reason.
            # This can include $$ and = and eval, but won't be evaluated
        END
    
    
        if [ "$1" = "-h" ]
        then
            echo "$USAGE" | cut -d "#" -f 2 | cut -c 2-
            return
        fi
    
        echo "foo"
    }
    

    So foo -h yields:

    This method prints foo to the terminal.
    
    Enter `foo -h` to see the docstring.
         It has indentations and multiple lines.
    
    Change the delimiter if you need hashtag for some reason.
    This can include $$ and = and eval, but won't be evaluated
    

    Explanation

    cut -d "#" -f 2: Retrieve the second portion of the # delimited lines. (Think a csv with "#" as the delimiter, empty first column).

    cut -c 2-: Retrieve the 2nd to end character of the resultant string

    Also note that if [ "$1" = "-h" ] evaluates as False if there is no first argument, w/o error, since it becomes an empty string.

提交回复
热议问题