Search code examples
bashmarkdowneofheredoc

Tab multiline variable to heredoc


I'm trying to add a multiline variable into a heredoc that will be put into a markdown file.

My script looks like this:

markdown=$(cat <<-EOF
<details>
    <summary>TEST</summary>

    ${output}
</details>
EOF
)

echo "$markdown" >> test.md

Where output is a multi line string:

this
is a
multiline
string

When I run the script the output looks like:

<details>
    <summary>TEST</summary>

    this
is a
multiline
string
</details>

How can I get it so that not just the first line of the output variable is tabbed correctly? I've tried running the variable through sed and adding tabs, but that doesn't work


Solution

  • You have to indent it. Yourself. For example, add 4 spaces in front of every line by using sed:

    cat <<-EOF
    <details>
        <summary>TEST</summary>
    
    $(sed 's/^/    /' <<<"$output")
    </details>
    EOF
    

    You could replace newlines with a newline and 4 spaces:

    cat <<-EOF
    <details>
        <summary>TEST</summary>
    
        ${output//$'\n'/$'\n'    }
    </details>
    EOF