Tab multiline variable to heredoc

101 Views Asked by At

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

2

There are 2 best solutions below

1
KamilCuk On BEST ANSWER

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
0
Ed Morton On

If you want leading tabs treated literally then don't tell the shell not to treat them literally, i.e. remove the - you had added before the first EOF:

cat <<EOF
    whatever
EOF

Not the problem you asked about but don't populate a variable from a here doc then echo it to a file, just redirect the cat output to a file:

cat <<EOF > file
    whatever
EOF

or if you want to store the text in a variable then don't use a here-doc:

markdown="<details>
    <summary>TEST</summary>

    $output
</details>"

printf '%s\n' "$markdown" > file