在Bash

时间:2016-07-27 08:08:14

标签: bash

我希望在将函数参数传递给下一个函数之前更改函数参数。

firstfunction() {
   # change "-f" to "--format" in arguments
   secondfunction "$@"
}

我尝试转换为数组,更改数组并转换回参数。但它看起来很复杂。是否可以使其更简单?

更新:更具体......

firstfunction data.txt -f "\d+"

应致电

secondfunction data.txt --format "\d+"

2 个答案:

答案 0 :(得分:1)

您可以使用getopts来可靠地解析和处理可选参数,如下所示:

firstfunction() {
   OPTIND=1
   local arr=()
   while getopts "f:x:" opt; do
      case $opt in
         f) arr+=("--format $OPTARG");;
         x) arr+=("--execute $OPTARG");;
      esac
   done
   echo "${arr[@]}"; # or call second function here
}

firstfunction -fabc -x foobar
--format abc --execute foobar

firstfunction -fabc -xfoobar
--format abc --execute foobar

firstfunction -f abc -xfoobar
--format abc --execute foobar

答案 1 :(得分:1)

这是一个非常棘手的问题。 Bash根本不擅长使用(稍微)复杂的数据结构,如数组。

我认为唯一可以想象的强大解决方案需要一个循环。这是我能想到的最简单的方法:

function firstfunction {
    local -A map=(['-f']='--format');
    local -a args=();
    local arg;
    for arg in "$@"; do
        if [[ -v map[$arg] ]]; then
            args+=("${map[$arg]}");
        else
            args+=("$arg");
        fi;
    done;
    echo ${args[@]+"${args[@]}"}; ## replace echo with secondfunction to run
};
firstfunction;
##
firstfunction a b;
## a b
firstfunction x -f -fff -f-f -fxy x-f \ -f -f\  -f;
## x --format -fff -f-f -fxy x-f  -f -f  --format

使用${args[@]+"${args[@]}"}代替"${args[@]}"进行最终扩展可以解决不明智的设计决策,如果你拥有{{{b}开发人员拒绝将空数组作为“未绑定变量” 1}}设置选项(nounset)已启用。请参阅Bash empty array expansion with `set -u`

替代:

set -u