Creating and using a user-defined hash table in a Bash script


Can anyone explain to me how to create (or simulate) a hash table in a Bash script in Linux?  I know that Bash uses some internal hash tables to store commands, but I need to create my own.


Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Why do you "need" to create your own?

Do you have a specific problem you are trying to solve?
doug5516Author Commented:
Hi, I need to create my own because as far as I know Bash does not have a hash data structure type (nor many other types that would be useful).  I need to be able to store and recall data using nonnumerical keys, therefore the need of a hash table.  I ended up using associative arrays, which while not the besh solution, worked for what I was trying to accomplish.
Associate arrays are just another name for a hash.

Again, without knowing what you really are trying to achieve, it is difficult to give you guidance.

If you really do need a hash, you are much better off using awk or Perl.
doug5516Author Commented:
I do not think that I would agree with you that associate arrays are just another name for a hash.  I would agree that associate arrays are one particular implementation of a hash (and not the best one) just as using a hash function, an array, and some collision policy would be another.  If you are trying to tell me that there is no good way to implement a hash table in bash and that I should consider using another language then your point is well taken.
Joshaven PotterConsultantCommented:
This isn't at all a hash but it almost acts like one... does this help:
typeset hash_${key}=$val
typeset hash_${key}=$val
### Tests ###
echo $hash_first
# produces => 3
echo "$(eval echo \$hash_${key})"
# produces => 3
echo $hash_second
# produces => sam

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Shell Scripting

From novice to tech pro — start learning today.