I want to create a nested associative array in bash and populate it in a loop. Here is the sample code that should print all the file names along with the corresponding Last Modification Time of that file in the current directory.
declare -A file_map
for file in *
do
declare -A file_attr
uuid=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)
file_attr['name']="$file"
file_attr['mod_date']=$(stat -c %y "$file")
file_map["$uuid"]=file_attr
done
for key in "${!file_map[@]}"
do
echo $(eval echo \${${file_map[$key]}['name']}) "->" $(eval echo \${${file_map[$key]}['mod_date']})
done
But it's only printing the information for a single file in the directory.
The output is coming as:
test.sh -> 2017-03-10 18:46:52.832356165 +0530
test.sh -> 2017-03-10 18:46:52.832356165 +0530
test.sh -> 2017-03-10 18:46:52.832356165 +0530
test.sh -> 2017-03-10 18:46:52.832356165 +0530
Whereas it should be, test.sh and 3 other different files.
Seems like declare -A file_attr is not creating any new associative array and as a result the previous values are getting overwritten. Any hep ?
a{k1}.b{k2}could be represented asx{k1.k2}. Isn't the flattening of the hash easier?file_map["$uuid"]=file_attrjust assigns adds the string "file_attr", not an array reference, to the array. I strongly recommend using a language with proper data structures instead ofbash. (As an additional benefit, you'l probably get a library that wraps thestatsystem call instead of having to run an external program for every file.)