関数の範囲内でのみ配列に追加

関数の範囲内でのみ配列に追加

、などになる可能性GETがあるREST API呼び出しを実行する関数を作成しています。PUTDELETEPOST

このメソッドを関数のパラメータとして提供し、その単一関数呼び出しのオプション配列に追加したいと思います。可能ですか?

現在私は別の配列を作成して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オプションを使用して、値やプロパティを変更せずに変数をローカルに作成できます。locallocal 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[@]}"
}

おすすめ記事