Reputation: 69
I am having an issue trying to set and populate an array who's name should be the value of another variable... can anyone help?
mainTID=${pidArray[$pidCounter]}
tempThreadIDs=`ps -eL | grep ${mainTID} | awk '{ if ( $2 != '$mainTID' ) print $2}'`
$mainTID=( $tempThreadIDs )
mainTID is an integer and I want to call the array whatever that integer is, and then populate it with the list called 'tempThreadIDs'
I thought about using eval, but I really need to keep my overhead down and I couldn't really get it to work correctly... I then attempted to just declare the array first, but I get an error stating that the value (an integer) is 'not a valid identifier'...am I not allowed to call an array a number?
Thanks in advance!
Upvotes: 0
Views: 205
Reputation: 75458
Unfortunately Bash does not support multi-dimensional arrays so you could just best store them as strings, but could be parsed easily:
Storing:
mainTID=${pidArray[$pidCounter]}
readarray -t VALUES < <(exec ps -eL | awk -v tid="$mainTID" '$1 == tid && $2 != tid { print $2 }')
IFS='|' eval 'STORAGE[$mainTID]="${VALUES[*]}"'
Using:
mainTID=${pidArray[$pidCounter]}
IFS='|' read -ra VALUES <<< "${STORAGE[$mainTID]}"
for V in "${VALUES[@]}"; do
# Do something with $V.
done
Note: STORAGE is an array variable there. It's quite enough with numbers. However if you're going to use keys besides numbers, just declare it as an associative array parameter before using:
declare -A STORAGE
Of course you can have your own preferred parameter names and case formats.
And as you may have noticed, I tried to simplify or correct your Awk command. I hope I did it right.
Another note: Using indirect parameter expansion pairing with a prefix+pid named variable is another good idea but would be a bulky pollution to the environment and confusing as you'd have to keep using a reference everytime you'd need to expand a value from the variable.
Upvotes: 1
Reputation: 80921
This section of the How can I use variable variables (indirect variables, pointers, references) or associative arrays? page of the BashFAQ
is likely going to be of some use here (though you really should read the whole page).
If you need to assign multiline values, keep reading.
A similar trick works for Bash array variables too:
# Bash/ksh93/mksh/zsh
typeset readFix=${BASH_VERSION+a}
aref=realarray
IFS=' ' read -d '' -r${readFix:-A} "$aref" <<<'words go into array elements'
echo "${realarray[1]}" # prints "go"
Upvotes: 1