OscarAkaElvis OscarAkaElvis - 4 months ago 11
Bash Question

Writing a bash script from bash script. Lines without interpretation

I want to create a bash script from a bash script. The problem doing it with old echo style (example echo -e "some commands" > /path/to/file.sh) is the commands are interpreted and substituted by its values.

Googling I found this solution on this forum:
Generating a bash script from a bash script

There, they use:

cat >/path/to/file.sh <<'EOF'
some commands
EOF


If I do a mini-script only with this, it works... the problem is while try to integrate in my big script... with a very basic "some commands"... it generates an error:

warning: here-document at line xxxx delimited by end-of-file (wanted `EOF') ./myscript.sh: line xxxx: syntax error: unexpected end of file

What am I doing wrong? can't be used this inside functions or what's the point of the error... I'm not sure of being understanding what error tries to say. Thank you.

Answer

The end delimiter for a here-document needs to be flush to the left, with no indentation whatsoever, regardless of whether it occurs in a function or elsewhere.

Indentation is allowed, but only with tabs, if the here-document is started with <<-word rather than with <<word (any initial tabs will then be removed from the start of each line of the here-document).

Also note that if the script that you are outputting with your bash script contains here-documents, then the delimiter of those here-documents must be different from the one used to end the contents of the script.

Since the delimiter may be an arbitrary word, it's good practice to use a descriptive delimiter, like END_SCRIPT, or similar.