1

I would like to write multiple lines to a file with the EOT, but the following script

#!/bin/bash
bench="X"
file_name="submit2.sh"
ids=(55)
for id in "${arrayName[@]}"; do
    cat <<'EOT' >> $bench/$file_name
    #!/bin/bash -l
    #PBS -l nodes=1:ppn=1
    echo $id
    EOT
done              # line 11

Gives this error

line 11: warning: here-document at line 6 delimited by end-of-file (wanted `EOT')
line 12: syntax error: unexpected end of file

How can I fix that?

mahmood
  • 1,211
  • Note that you have various issues here: i) ids=(55) just sets the variable $id to the string 55; ii) for id in "${arrayName[@]}"; do will fail since you don't define arrayName anywhere; iii) even if that did work, you would still always be writing to X/submit2.sh, since the values of $bench and $file_name never change. – terdon Sep 13 '22 at 15:03

1 Answers1

2

The end-delimiter of the here-document must be the first thing on the line:

for ...; do
    cat <<END_SUBMIT_SCRIPT
#!/bin/bash

... ...

END_SUBMIT_SCRIPT done

If you want to indent the lines in the script that creates the submission script, then use literal tabs at the start of the lines and do the redirection using <<-DELIMITER, e.g.

for ...; do
    cat <<-END_SCRIPT
        #!/bin/bash
        ...
        ...
        END_SCRIPT
done

The - in <<- will cause all initial tabs (not spaces) to be removed from each line of the here-document. This also allows you to indent the end delimiter, as shown above.

Also note that if you want to expand a variable in the here-document, you should not quote the here-document delimiter.

Kusalananda
  • 333,661
  • You didn't specify the file name in the cat line. – mahmood Sep 13 '22 at 13:15
  • @mahmood I did not, since I did not intend to rewrite your code but instead to show how to indent a here-document properly. To write the output of cat to a file, you still would do it as you do in your code, with cat >>filename. – Kusalananda Sep 13 '22 at 13:16
  • Not a correction, just a comment about here document indenting: I made the choice long ago to not indent here documents. This usually means I put a one-line comment before the here document telling my co-workers that the next set of lines are intentionally not indented (so they don't try to "fix" the lines). In some cases I move there here document to a separate shell function/subroutine so the lack of indentation doesn't ruin the readability of the code where it's used. – Sotto Voce Sep 13 '22 at 18:55