问题描述
在 bash
中是否存在这样的事情,或者至少有类似于前向声明的类似(解决方法),例如C / C ++中众所周知的?
Is there such a thing in bash
or at least something similar (work-around) like forward declarations, well known in C / C++, for instance?
或者有这样的事情,因为例如它总是以一次执行(一行一行)?
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.
例如:
# something like forward declaration
function func
# execution of the function
func
# definition of func
function func
{
echo 123
}
推荐答案
好的问题。对于我的大部分脚本,我都使用这种模式:
Great question. I use a pattern like this for most of my scripts:
#!/bin/bash
main() {
foo
bar
baz
}
foo() {
}
bar() {
}
baz() {
}
main "$@"
您可以从上至下阅读代码,但直到最后一行才会开始执行。通过将$ @
传递给main(),您可以访问命令行参数 $ 1
, $ 2
,等等。就像你平常那样。
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.
这篇关于在Bash或Shell脚本中转发函数声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!