jes*_*e_b 3 bash array function
我正在写一个函数,这将使一个REST API调用这可能是要么GET
,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[@]}"
Run Code Online (Sandbox Code Playgroud)
我也可以使用一个临时数组来存储 的内容options
,添加新选项,然后在函数结束之前重置它,但我认为这也不是一个特别干净的方法。
对于 bash 5.0 及更高版本,您可以使用localvar_inherit
导致local
行为类似于基于 ash 的 shell 的选项,即在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
Run Code Online (Sandbox Code Playgroud)
对于任何版本,您还可以执行以下操作:
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[@]}"
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
166 次 |
最近记录: |