首页 > 解决方案 > 在函数中导出的 bash 脚本中的变量

问题描述

我在脚本中有一个函数,我想在其中扩展一个变量。我该怎么做?

例如:

set_function.sh:

function test_funct {some_binary --configfile="$1"/folder/; }
export -f test_funct

我希望这样,如果我打电话:

./set_function.sh /some/path/here

传递的变量 /some/path/here 得到扩展,因此如果我再调用

test_funct --some-other-flag

我不明白:

some_binary --configfile=--some-other-flag/some_path/

反而

some_binary --configfile=/some/path/here/folder/ --some-other-flag

标签: bashfunction

解决方案


似乎您需要使用变量,如下所示:

test_func() {
    some_binary --config $CONFIG_PATH/folder/ "$@"
}

并称它为

CONFIG_PATH=~/config1 test_func --verbose
export CONFIG_PATH=~/config2
test_func --quiet

另请注意,您不能向上导出内容,即不能调用set_function.sh以便test_func导出到调用外壳。你需要. set_function.sh或同样source set_function.sh代替。


推荐阅读