Ben Bacarisse <
ben.u...@bsb.me.uk>:
> Helmut Waitzmann <
nn.th...@xoxy.net> writes:
>
>> But you can always do it like this: For every script to be
>> embedded inside a shell script, procede using the following
>> rules: In the script to be embedded, replace each single quote
>> by a single quote, a backslash, and 2 single quotes
>> [alternatives elided...]
>
> That works well when there is a "build process" for the script that
> contains the embedded script because, as you say, it's easy to automate.
> But I find it fragile when the embedded script might be edited and hard
> to read when the script needs to be inspected. Lots of '\''...'\''s get
> in the way.
Yes, that's true. In this case, I either include the script to
be embedded in its original form, each line of it preceded by
#
in the shell script as well, that is, save it as a shell comment
for a later source of re-editing.
Or, when the embedded script is to be to re-edited, construct a
shell command to be run: Start that command with the shell
command line fragment
printf '%s' \
then copy and paste the embedded script, which is to be
re-edited, into the following lines, either in a shell script
file or use the features of your favourite editor to run a shell
command line. Then run that shell script file (resp. the shell
command line).
The standard output will be the original script to be embedded.
> My preference is for here documents. You can choose a clear and
> staggeringly unlikely delimiter, and the text between the start and the
> end is taken literally (if you 'quote-the-end-delimiter').
>
> This works best for standard input, but when I need a single string
> argument I put "$(cat in front and )" at the end. Not pretty, perhaps,
> but it keeps all of the mess away from the actual embedded script:
>
> printf "{%s}\n" "$(cat <<'---END-OF-EMBEDDED-SCRIPT---'
> ...script here...
> ---END-OF-EMBEDDED-SCRIPT---
> )"
When using here documents, I tend to use
cut -d . -f2- <<-EOF
.These are the lines of the script to be embedded,
.each of them prepended with the "cut" delimiter.
.Even indented lines like the following
. indented line
.will have their indentation preserved.
EOF
rather than just "cat", prepending each line of the script to be
embedded with a non-whitespace delimiter (for example a period):
That allows me to neatly indent the here document using TAB
characters according to the indentation level of its context in
the shell script and also frees me from having to worry about
looking for a suitable here document delimiter: "EOF" (for
example) will always work, as it is different from any line
starting with zero or more white space characters followed by a
period.