I was trying to demonstrate the use of an associative arrary to gather counts. It is working in the while loop, but it appears to have lost all its information after the while loop. What am I doing wrong? All echo statements except for the one in the for loop have been added for debugging.
#!/bin/bash
declare -A shell_type
shells=$(cut -d: -f7 /etc/passwd)
echo "$shells"|
while read sh
do
if [ -z "${shell_type[$sh]}" ]
then
shell_type[$sh]=1
else
let "shell_type[$sh] += 1"
fi
echo "$sh ${shell_type[$sh]}"
echo "${!shell_type[*]}"
echo "${shell_type[*]}"
done
echo "${shell_type[*]}"
for var in "${!shell_type[*]}"
do
echo "$var count is ${shell_type[$var]}"
done
shopt -s last pipeto allow the last command of a pipeline to execute in the current shell (not a subshell), which eliminates your problem.