I basically want to write me a bash script, where I'd generate a couple of big files using heredoc; and then run some commands using those files.
It is understood that (obviously) the heredoc files need to be generated before the commands run - however, what irritates me in that arrangement, is that I must also write the 'heredoc' statements code, before I write the command code.
So I thought I'd write the heredoc statements in a function - but still the same problem here: Chapter 24. Functions says:
The function definition must precede the first call to it. There is no method of "declaring" the function, as, for example, in C.
Indeed, it is so:
$ cat > test.sh <<EOF
testo
function testo {
echo "a"
}
EOF
$ bash test.sh
test.sh: line 1: testo: command not found
Then I thought maybe I could place some labels and jump around with GOTO
, as in (pseudocode):
$ cat > test.sh <<EOF
goto :FUNCLABEL
:MAIN
testo
goto :EXIT
:FUNCLABEL
function testo {
echo "a"
}
goto MAIN
:EXIT
... but it turns out BASH goto doesn't exist either.
My only goal is that - I want to first write the "core" of the script file, which is some five-six commands; and only then write the heredoc statements in the script file (which may have hundreds of lines); having the heredocs first really makes reading the code difficult for me. Is there any way to achieve that?
A common technique is:
In Bash you will have to define the entire function before calling it. If you want to write the core script first then you can write the heredoc statements in another script file and call it whenever you feel like and assign the values returned (may be) to your core script.
BASH scans the file linearly and executes statements as it comes across them, just like it does when you're on the command line. There are two ways I see to do what you want. First, you could write the code-generating heredoc, etc. in a separate file (say helperfile.sh) and source it with
. helperfile.sh
. That's probably best. You could also write a function (main
perhaps) in the beginning that does what you want, then the heredoc code, then at the bottom callmain
.