2016-07-27 5 views
2

関数の引数を次の関数に渡す前に変更したいと思います。Bashの関数引数を変更する

firstfunction() { 
    # change "-f" to "--format" in arguments 
    secondfunction "[email protected]" 
} 

私は配列に変換し、配列を変更して引数に戻そうとしました。しかし、それはとても複雑に見えます。簡単にすることは可能ですか?

UPDATE:より具体的には...

firstfunction data.txt -f "\d+" 

あなたはこのような信頼性の高い解析およびプロセスオプションの引数にgetoptsを使用することができます

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

@anubhavaのは、私が長いオプションに短いオプションを変更する必要があると仮定しましょう:-f - > --format、-x - > --execute。 –

答えて

1

これは驚くほど難しい問題です。 Bashは配列のような(やや)複雑なデータ構造を扱うのはあまり良くありません。

考えられる唯一の堅牢なソリューションにはループが必要だと思います。これは、私は考えることができる最も簡単な方法です:

${args[@]+"${args[@]}"}だけではなく "${args[@]}" bashの開発者は、「結合していない変数」として空の配列を拒否するように作られた無分別なデザインの決定の周りに、最終的な拡張工事のためを使用して
function firstfunction { 
    local -A map=(['-f']='--format'); 
    local -a args=(); 
    local arg; 
    for arg in "[email protected]"; 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 

nounset設定オプション(set -u)が有効になっている場合。 Bash empty array expansion with `set -u`を参照してください。


代替:簡単にするために

function firstfunction { 
    local -A map=(['-f']='--format'); 
    local -a args=("[email protected]"); 
    local -i i; 
    for ((i = 0; i < ${#args[@]}; ++i)); do 
     if [[ -v map[${args[i]}] ]]; then 
      args[i]="${map[${args[i]}]}"; 
     fi; 
    done; 
    echo ${args[@]+"${args[@]}"}; ## replace echo with secondfunction to run 
}; 
+1

ありがとう@bgoldst!私は@ anubhavaのソリューションで遊んでいましたが、実際にはより一般的なものを必要とするよりも実現しました。 –

+0

ニックピッキングではありませんが、 'firstfunction -fabc'は' -f'オプションで 'abc'を送る有効なオプション引数です。一般的には '--format abc'または' --format = abc'になります。 – anubhava

+0

もっと単純なループを使うことができます: 'for $"; 〜する – chepner

1

を呼び出す必要があります:

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 
+0

はい、正しい@bgoldstです。これを処理する完全な方法については、 'while getopts'を使ってループを提案してください。 – anubhava

関連する問題