问题
I am trying to make a hash table with the file name of all files in a directory and another integer number. Like "File Name" : "number". The code should be in bash 4.x. This is the code which I wrote:
#!/bin/bash
DIR=`ls`
declare -A ARRAY
ZERO=0
for FILES in $DIR
do
echo "We have $FILES"
ARRAY+=(["$FILES"]="$ZERO")
done
echo "Done with filling up array!"
for file in "${ARRAY[@]}" ; do
KEY="${file%%:*}"
VALUE="${file##*:}"
printf "%s has number %s.\n" "$KEY" "$VALUE"
done
echo "We are done here!"
echo "Check: "
printf "%s has the number %s\n" "${ARRAY[1]%%:*}" "${ARRAY[1]##*:}"
and it gives this output:
[Anil@computer68 test]$ bash kenzo.sh
bash kenzo.sh
We have dafuq.sh
We have hello.cpp
We have kenzo.sh
Done with filling up array!
0 has number 0.
0 has number 0.
0 has number 0.
We are done here!
Check:
has the number
How do I fix it? None of the elements in the hash table have any values of the file name and the number.
回答1:
In your case you receives only the values from the array, which are always '0'. To get the keys of an associative array, use
for file in "${!ARRAY[@]}" ; do
(Mind the ! before the name of the associative array). You can print the value of the array using the ${ARRAY[$file]} notation. Contrary to normal arrays here the $ is needed, otherwise it returns the file indexed. Anyway here the returned value will be always '0'.
So the second loop could be:
for KEY in "${!ARRAY[@]}" ; do
VALUE="${ARRAY[$KEY]}"
printf "%s has number %s.\n" "$KEY" "$VALUE"
done
Comments
- I see no point to use associative arrays here. Simple array should do.
- Why do you cut the
:character? As I see it is not part of the file names. Maybe You think that the element of an associative array is inKEY:VALUEform. It is not. The index of theARRAYisKEYand the value isVALUE. - Instead of
DIR=`ls`andfor FILES in $DIR;...you could usefor FILES in *; .... - This is correct:
ARRAY+=(["$FILES"]="$ZERO"), but you can useARRAY[$FILES]="$ZERO"form as well. It is a little bit more talkative.
来源:https://stackoverflow.com/questions/17142415/appending-to-a-hash-table-in-bash