在 Bash 或 Shell 脚本中转发函数声明?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13588457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Forward function declarations in a Bash or a Shell script?
提问by Kiril Kirov
Is there such a thing in bash
or at least something similar (work-around) like forward declarations, well known in C / C++, for instance?
例如bash
,在 C/C++ 中众所周知的前向声明中是否有这样的东西或至少是类似的(变通方法)?
Or there is so such thing because for example it is always executed in one pass (line after line)?
或者有这样的事情,因为例如它总是在一次传递中执行(一行接一行)?
If there are no forward declarations, what should I do to make my script easier to read. It is rather long and these function definitions at the beginning, mixed with global variables, make my script look ugly and hard to read / understand)? I am asking to learn some well-known / best practices for such cases.
如果没有前向声明,我该怎么做才能使我的脚本更易于阅读。它很长,开头的这些函数定义与全局变量混合在一起,使我的脚本看起来很丑陋且难以阅读/理解)?我要求为这种情况学习一些众所周知的/最佳实践。
For example:
例如:
# something like forward declaration
function func
# execution of the function
func
# definition of func
function func
{
echo 123
}
回答by John Kugelman
Great question. I use a pattern like this for most of my scripts:
很好的问题。我的大多数脚本都使用这样的模式:
#!/bin/bash
main() {
foo
bar
baz
}
foo() {
}
bar() {
}
baz() {
}
main "$@"
You can read the code from top to bottom, but it doesn't actually start executing until the last line. By passing "$@"
to main() you can access the command-line arguments $1
, $2
, et al just as you normally would.
您可以从上到下阅读代码,但它实际上直到最后一行才开始执行。通过传递"$@"
给 main(),您可以像往常一样访问命令行参数$1
、$2
、 等。
回答by mouviciel
When my bash scripts grow too much, I use an include mechanism:
当我的 bash 脚本增长太多时,我使用包含机制:
File allMyFunctions
:
文件allMyFunctions
:
foo() {
}
bar() {
}
baz() {
}
File main
:
文件main
:
#!/bin/bash
. allMyfunctions
foo
bar
baz