2

I'm writing a function that will make a REST API calls which could be either GET, PUT, DELETE, POST, etc.

I would like to feed this method to the function as a parameter and add it to the options array for that single function call. Is this possible?

Currently I am solving this by creating a separate local array but would prefer to only use the single options array.

#!/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[@]}"

I could also use a temporary array to store the contents of options, add the new options, and then reset it before the function ends, but I don't think that is a particularly clean method either.

4

One option would be to explicitly use a subshell for the function, then override its local copy of the array, knowing that once the subshell exits, the original variable is unchanged:

# a subshell in () instead of the common {}, in order to munge a local copy of "options"
some_func () (
    local urn=$1
    shift
    options+=("$@")
    printf '%s\n' "${options[@]}"
)
5

With bash 5.0 and above, you can use the localvar_inherit option which causes local to behave like in ash-based shells, that is where local var makes the variable local without changing its value or attributes:

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

With any version, you can also do:

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[@]}"
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.