我希望将配置变量保持在最顶层,但它们依赖于需要在其上方的其他变量。我怎么能(如果可能的话)在 config 部分下面移动不要触摸部分?
举例说明:
#!/bin/bash
#== don't touch ==
dirpath=$(dirname "$1")
dirname=$(basename $(dirname "$1"))
#== config ==
path="$dirpath" #using the value of $dirpath straight in config would be ugly.
name="$dirname"
echo "$path" + "$name"
..但我希望将 config 移到其他所有位置:
#!/bin/bash
#== config ==
path="$dirpath" #using the value of $dirpath straight in config would be ugly.
name="$dirname"
#== don't touch ==
dirpath=$(dirname "$1")
dirname=$(basename $(dirname "$1"))
echo "$path" + "$name"
答案 0 :(得分:2)
<强>更新强>
通常的模式是:
#!/bin/bash
function main()
{
prepare
do_step1 args ...
do_step2 args ...
do_step3 args ...
do_step4 args ...
exit 0
}
function prepare() { .... }
function do_step1() { ....}
function do_step2() { ....}
function do_step3() { ....}
function do_step4() { ....}
// entry point
main
只要(子)函数定义在调用之前,就可以很好地找到它们。
直译答案:
不,你需要有这个功能,或者你需要:
export dynamic="interesting"
function getsomething() { echo -n "$dynamic"; }
export dynamic="stuff"
echo "$(getsomething)"
将显示“stuff”,而非“有趣”
评估方法:
export param=value1
export dependent='$param' # (note the SINGLE quotes)
export param=value2
eval "echo $dependent"
将打印“value2”,而不是“value1”
如果它只是不要触摸源文件包含:
source donot_touch.sh