Bash - defining a script write function after the first call (as a GOTO / jump problem)

I basically want to write me a bash script where I would generate a couple of large files using heredoc ; and then run some commands using these files.

Itโ€™s clear that (obviously) heredoc files must be generated before executing the commands, however, which annoys me in this layout, I must also write the โ€œheredocโ€ instruction code before writing the command code.

So, it seemed to me that I would write heredoc instructions in functions, but still the same problem: Chapter 24. Functions says:

A function definition must precede the first call. There is no method for "declaring" a function, for example, in C.

Indeed, this 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 that maybe I could place some tags and jump using 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 also does not exist.

My only goal is to first write the "core" of a script file, which consists of several commands from five to six; and only then write the heredoc statements in the script file (which may contain hundreds of lines); with heredocs at first really makes reading code difficult for me. Is there any way to achieve this?

+7
source share
3 answers

The general method is:

  #! / bin / sh

 main () {
   cmd_list
 }

 cat> file1 << EOF
 big herdoc
 Eof

 main
+15
source

In Bash, you will need to define the entire function before calling it. If you want to write the script core first, then you can write the heredoc instructions in another script file and call it whenever you want, and assign the values โ€‹โ€‹returned (maybe) to your script core.

+3
source

BASH scans the file linearly and executes the instructions as they appear, as happens when you are on the command line. There are two ways to do what you want. First, you can write heredoc generating code, etc. In a separate file (for example, helperfile.sh) and specify it with . helperfile.sh . helperfile.sh . This is probably the best. You could also write a function ( main perhaps) at the beginning that does what you want, then the heredoc code, and then the bottom call to main .

+3
source

All Articles