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

独自空忆成欢 提交于 2019-11-29 14:47:12

问题


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?


回答1:


A common technique is:

#!/bin/sh

main() {
  cmd_list
}

cat > file1 << EOF
big HEREDOC
EOF

main



回答2:


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.




回答3:


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 call main.



来源:https://stackoverflow.com/questions/8249040/bash-writing-function-definition-in-script-after-first-call-as-a-goto-jump-pr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!