在 Bash 或 Shell 脚本中转发函数声明?

bash中有这样的东西吗? 或者至少有类似的东西(解决方案) ,比如在 C/C + + 中众所周知的正向声明?

或者有这样的事情,因为例如,它总是在一个通道(一行又一行)执行?

如果没有转发声明,我应该做什么来使我的脚本更容易阅读。它相当长,而且这些函数定义在开始时混合了全局变量,使我的脚本看起来很丑陋,难以阅读/理解) ?我要求学习一些众所周知的/最佳的做法,为这种情况。


例如:

# something like forward declaration
function func


# execution of the function
func


# definition of func
function func
{
echo 123
}
26044 次浏览

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.

When my bash scripts grow too much, I use an include mechanism:

File allMyFunctions:

foo() {
}


bar() {
}


baz() {
}

File main:

#!/bin/bash


. allMyfunctions


foo
bar
baz

You can have the script source portions of itself:

#!/bin/bash
. <( sed -n '/^#SOURCE-BEGIN/,/^#SOURCE-END/{//!p;}' $0 )
greeting "$@"
foo hey


#SOURCE-BEGIN
greeting() {
for i in "$@"
do
echo ">[$i]"
done
}


foo() {
echo in foo
echo "arg passed in: $1"
}
#SOURCE-END


echo good bye
$ ./myscript.sh hello world "one string"
>[hello]
>[world]
>[one string]
in foo
arg passed in: hey
good bye

I used process substitution (<(....)) to source the output of the sed command. The sed syntax comes from here, search for What about the classic sed solution?