、などになる可能性GET
があるREST API呼び出しを実行する関数を作成しています。PUT
DELETE
POST
このメソッドを関数のパラメータとして提供し、その単一関数呼び出しのオプション配列に追加したいと思います。可能ですか?
現在私は別の配列を作成してlocal
この問題を解決していますが、単一のoptions
配列のみを使用することを好みます。
#!/bin/bash
options=(
--user me:some-token
-H "Accept: application/json"
)
some_func () {
local urn=$1
shift
local func_opts=("${options[@]}" "$@")
printf '%s\n' "${func_opts[@]}"
}
# This should return all options including -X GET
some_func /test -X GET
# This should return only the original options
printf '%s\n' "${options[@]}"
また、一時的な配列を使用して内容を保存し、新しいoptions
オプションを追加してから関数が終了する前にリセットすることもできますが、この方法も特にきちんとしたアプローチではないと思います。
ベストアンサー1
Bash 5.0以降では、アクションをAshベースのシェルのように動作させるlocalvar_inherit
オプションを使用して、値やプロパティを変更せずに変数をローカルに作成できます。local
local var
shopt -s localvar_inherit
options=(
--user me:some-token
-H "Accept: application/json"
)
some_func () {
local urn=$1
shift
local options # make it local, does not change the type nor value
options+=("$@")
printf '%s\n' "${options[@]}"
}
some_func /test -X GET
すべてのバージョンで次のこともできます。
some_func () {
local urn=$1
shift
eval "$(typeset -p options)" # make a local copy of the outer scope's variable
options+=("$@")
printf '%s\n' "${options[@]}"
}