Mailing List Archive

Support open source code!


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[tlug] Bash syntax question



I want to pass a set of array values to a function in a Bash script.
Something like this:


  function ask_questions () {
    ARRAY=($1)
    for i in "${ARRAY[@]}"; do
      echo "What is ${i}?"
    done
  }
  
  TMP=("paul cobrafesta" "sdfsda" "beano garble" "qazxi")
  ...
  ask_questions <expression of TMP>


But I haven't been able to find a way to express TMP as a positional parameter
that does not lose its array structure.  "${TMP[*]}" returns a single word,
and if it's split you get six items in the above example.  "${TMP[@]}" returns
four items, which gives you four parameters -- in this example that need not
be a problem (I could use "$@" for the assignment), but it's ugly, and if
there are other parameters to the function, things will break.

I thought of passing the string, "TMP", and then expanding it inside the
function, but I can't find a way of doing that either -- neither "set" nor
"declare" seem to offer this service, and nested expansions give me a "bad
substitution" error.

I'm stumped.  Can anyone help?  I can think of at least one awkward way to
sneak around around this problem, but I'm trying to keep the code from
becoming a tangled and illegible mass of white noise.  (The question that will
follow is, "Then why not write it in something other than bash?" But that's
another story ...)

Cheers,
Frank
Nagoya


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links