Bash-首次调用后在脚本中编写函数定义(作为GOTO/跳转问题) [英] Bash - writing function definition in script after first call (as a GOTO/jump problematics)

查看:121
本文介绍了Bash-首次调用后在脚本中编写函数定义(作为GOTO/跳转问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上想写一个bash脚本,在其中我将使用 heredoc ;然后使用这些文件运行一些命令.

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.

可以理解,(显然)在运行命令之前需要生成Heredoc文件-但是,令我烦恼的是,我还必须在之前编写"heredoc"语句代码,

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.

所以我想我会在函数中编写Heredoc语句-但这里仍然是相同的问题:

So I thought I'd write the heredoc statements in a function - but still the same problem here: Chapter 24. Functions says:

函数定义必须在第一次调用它之前.没有诸如在C语言中那样声明"功能的方法.

The function definition must precede the first call to it. There is no method of "declaring" the function, as, for example, in C.

确实如此:

$ cat > test.sh <<EOF
testo

function testo {
  echo "a"
}
EOF

$ bash test.sh 
test.sh: line 1: testo: command not found

然后我想也许我可以放置一些标签并用GOTO跳转,如(伪代码):

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

...但是事实证明 BASH goto 也不存在.

... but it turns out BASH goto doesn't exist either.

我唯一的目标是-我想首先编写脚本文件的核心",这是一些五到六个命令.并且只有 then 在脚本文件中写入heredoc语句(可能有数百行);首先拥有heredocs确实使我很难阅读代码.有什么办法可以做到这一点?

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?

推荐答案

一种常见的技术是:


#!/bin/sh

main() {
  cmd_list
}

cat > file1 << EOF
big HEREDOC
EOF

main

这篇关于Bash-首次调用后在脚本中编写函数定义(作为GOTO/跳转问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆