Using pathname as a key in an associative array does not work when array is declared inside of a different function

Viewed 23

Long time listener, first time caller here: So, let's say, for whatever reason, I really want to use the names of files as my keys in an associative array, for example, /dev/sda. For some unholy reason, if I declare the array inside a separate function, for example, an init function,

somefunction() { declare -A driveArray; }
somefunction

and then later, in another function (or even outside a function), it abjectly fails when I attempt to file something away as a key referenced by a string that happens to also correspond to a path

drv="/dev/sda"               # or ${"/dev/sda"} or without quotes.  
driveArray[$drv]=$(readSMART $drv)

# or if I do it like this
for _isd3 in "${!_tmpsmarts[@]}"; do 
    local _sfile="${_tmpsmarts[$_isd3]}";
    driveARRAY[${_isd3}]=$(< $_sfile); 
    rm $_sfile; 
done;

Frankly, if I do it in any way that references a path, I get the always fun:

./testbed.sh: line 177: /dev/sda: syntax error: operand expected (error token is "/dev/sda")

Meanwhile, cut and paste the declaration outside of a function and, boom, works just fine.

Well, that just cost me a solid 3 hours. At this point in the project, it would have been easier to learn python from scratch and have used that. What, pray tell, WHAT is the possible difference here?? Also, just to save everyone the time, it is not lost on me that ye olde ' ' would work here, but I need to pass things around by reference, or, at least, I WANT to, so, that's where we are with that.

1 Answers

declare in a function acts like local; the variable only exists in the scope of the function. The -g option makes it a global definition instead.

somefunction() { declare -gA driveArray; }
Related