You are not logged in.

#1 2010-10-17 04:18:54

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,722

[Bash] How to `declare` a global variable inside a function?

#!/bin/bash

# Not using declare -A, array will be treated as indexed array rather than an associative array
seta()
{
  for ((n=0;n<$1;n++)); do
    printf -v a_$n[k] %s k$n
    printf -v a_$n[j] %s j$n
    eval echo inside seta: a_$n[k] = \$\{a_$n\[k\]\}
  done
}
seta 3
echo outside: a_0[k] = ${a_0[k]}
echo outside: a_0[j] = ${a_0[j]}
echo

# Use declare -A inside function, array will be undefined outside
setb()
{
  for ((n=0;n<$1;n++)); do
    declare -A b_$n # Note here
    printf -v b_$n[k] %s k$n
    printf -v b_$n[j] %s j$n
    eval echo inside setb: b_$n[k] = \$\{b_$n\[k\]\}
  done
}
setb 3
echo outside: b_0[k] = ${b_0[k]}
echo outside: b_0[j] = ${b_0[j]}
echo

# The bad solution, only works if we know beforehand how many c_? arrays will be assigned inside setc()
for ((n=0;n<3;n++)); do
  declare -A c_$n
done
setc()
{
  for ((n=0;n<$1;n++)); do
    printf -v c_$n[k] %s k$n
    printf -v c_$n[j] %s j$n
    eval echo inside setc: c_$n[k] = \$\{c_$n\[k\]\}
  done
}
setc 3
echo outside: c_0[k] = ${c_0[k]}
echo outside: c_0[j] = ${c_0[j]}

My original code does the declare -A as in setb(). I was surprised when I saw all blank output... Now the problem is illustrated clearly by the setb() example.
The setc() example works, but a bit ugly: look at the two 3's...
My ideal solution would be, something like `declare_global -A b_$n` in setb()
Any ideas?


This silver ladybug at line 28...

Offline

#2 2010-10-19 17:09:50

kachelaqa
Member
Registered: 2010-09-26
Posts: 216

Re: [Bash] How to `declare` a global variable inside a function?

with current bash versions, i don't think it is possible to declare global associative arrays in functions.

what you are after is the "-g" option of typeset which is available in zsh.

i think i read somewhere that something similar may be planned for bash 4.2.

Offline

Board footer

Powered by FluxBB