I have the same exact problem as described in this SO post ("bash associative array key string with colon is giving error"): https://stackoverflow.com/q/40406187/10639803
The solution is to use declare -A
but once I do this, my associative array ceases being global.
Is there a way to declare -A
and having it global?
UPDATE: I tried declare -gA
as described here: https://stackoverflow.com/a/21151984/10639803 but it doesn't work for me for some reason: As soon as exit the loop that populates my associative array (hashmap), the array gets unset.
Here is the actual bash code (the echo commands inside the loop are to verify that values are indeed extracted and assigned):
declare -gA HOSTS_START_MAP
find "$TEMP" -type f -name "debug.log*" -exec grep -F "STARTING HOST " {} \; |
while IFS= read -r HOST_START_LINE; do
if [[ $HOST_START_LINE =~ (.*)(DEBUG)(.*)(STARTING HOST)([ 0-9]*)(.*)(CALCULATION) ]]
then
HOST_START_TIME=$(echo "${BASH_REMATCH[1]}" | xargs)
HOST_NAME=$(echo "${BASH_REMATCH[6]}" | xargs)
# echo ">$HOST_NAME< ... >$HOST_START_TIME<"
HOSTS_START_MAP[$HOST_NAME]=$HOST_START_TIME
# echo $HOST_NAME --- ${HOSTS_START_MAP[$HOST_NAME]}
fi
done
echo ${#HOSTS_START_MAP[@]}
for MYKEY in "${!HOSTS_START_MAP[@]}"; do echo $MYKEY --- ${HOSTS_START_MAP[@]}; done
shopt -s lastpipe
or make the loop read from a process substitution withwhile ... done < <(find ...)
(see e.g. Ilkkachu's answer on the dupe). – Kusalananda Nov 26 '19 at 21:04