I made an associative array as follows. To give a few details, the keys refer to specific files because I will be using this array in the context of a larger script (where the directory containing the files will be a getopts argument).
declare -A BAMREADS
echo "BAMREADS array is initialized"
BAMREADS[../data/file1.bam]=33285268
BAMREADS[../data/file2.bam]=28777698
BAMREADS[../data/file3.bam]=22388955
echo ${BAMREADS[@]} # Output: 22388955 33285268 28777698
echo ${!BAMREADS[@]} # Output: ../data/file1.bam ../data/file2.bam ../data/file3.bam
So far, this array seems to behave as I expect. Now, I want to build another associative array based on this array. To be specific: my second array will have the same keys as my first one but I want to divide the values by a variable called $MIN.
I am not sure which of the following strategies is best and I can't seem to make either work.
Strategy 1: copy the array and modify the array?
MIN=33285268
declare -A BRAMFRACS
echo "BAMFRACS array is initialized"
BAMFRACS=("${BAMREADS[@]}")
echo ${BAMFRACS[@]} # Output: 22388955 33285268 28777698
echo ${!BAMFRACS[@]} # Output: 0 1 2
This is not what I want for the keys. Even if it works, I would then need to perform the operation I mentioned on all the values.
Stragegy 2: build the second array when looping through the first.
MIN=33285268
declare -A BRAMFRACS
echo "BAMFRACS array is initialized"
for i in $(ls $BAMFILES/*bam)
do
echo $i
echo ${BAMREADS[$i]}
BAMFRACS[$i] = ${BAMREADS[$i]}
done
echo ${BAMFRACS[@]}
echo ${!BAMFRACS[@]}
#When I run this, I get the following error which I am unsure how to solve:
../data/file1.bam
33285268
script.bash: line 108: BAMFRACS[../data/file1.bam]: No such file or directory
../data/file2.bam
28777698
script.bash: line 108: BAMFRACS[../data/file2.bam]: No such file or directory
../data/file3.bam
22388955
script.bash: line 108: BAMFRACS[../data/file3.bam]: No such file or directory
Thanks
bash
(≥4.4) you can shorten to `typeset -A h2="${h1_definition#=}". I was confused why this wasn't working for me on CentOS 7 (Bash 4.2.x) so I tried 3.x through 5.x by [pulling images from Docker](https://gist.github.com/ernstki/b782cc7f2a29ec01c1f4355f2dd312cc), and with earlier Bashes you'll either get an error or just a literal string assigned to
[0]` instead (but no error). – Kevin E Mar 14 '21 at 05:18typeset
instead ofdeclare
? Judging fromhelp typeset
it seemsdeclare
is the "real" command. – MestreLion Sep 10 '21 at 14:52typeset
is the name ksh chose nearly 40 years ago and is supported by all Bourne-like shells that have variable types including bash, so that's the one I'm used to. bash decided to call itdeclare
for some reason, but has always supportedtypeset
as an alias and will likely support it forever, like other shells. There have been more shells recently addingdeclare
as an alias fortypeset
for compatibility withbash
, but it will take more than that to change my habits :-) – Stéphane Chazelas Sep 10 '21 at 14:57