Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - writing function definition in script after first call (as a GOTO/jump problematics)

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?

like image 347
sdaau Avatar asked Nov 23 '11 21:11

sdaau


1 Answers

A common technique is:

#!/bin/sh

main() {
  cmd_list
}

cat > file1 << EOF
big HEREDOC
EOF

main "$@"
like image 115
William Pursell Avatar answered Nov 12 '22 19:11

William Pursell