How to Properly Create Multi-Dimensional Arrays in Bash?
Asked by
CuriousCoder32
I'm trying to create a script that mimics multi-dimensional arrays for a personal project. I generate surnames, traits, and more, but I feel like I'm going about it the wrong way. Currently, I'm using `declare` commands and trying to create connected items, but it's becoming confusing. I'd really appreciate any tips or suggestions on how to structure this better!
Answers
It sounds like you're trying to handle a lot of complexity with arrays. Instead of using `eval`, which can lead to some unpredictable results, think about storing your data in files if possible. For instance, create a directory and use files named after each name to store their characteristics. Linux handles files really well, so it might simplify your script! Plus, hereโs a helpful resource on why you should avoid `eval`: [link](https://stackoverflow.com/questions/17529220/why-should-eval-be-avoided-in-bash-and-what-should-i-use-instead).
Reply to this answer
When declaring arrays, make sure not to use the `$` symbol. For example, instead of `declare -a $name`, just use `declare -a name`. Using `$name` is attempting to reference the value, not declare the array you want. This simple change can save you quite a bit of trouble!
SyntaxNinja: Oh, I see! That makes a lot more sense.
CommandLineWhiz: This is good to know; I often mess that up!
Reply to this answer
For complex data storage, consider using associative arrays. You can combine multiple keys into a single string as the key for storing values. Here's a neat little example:
```bash
key() {
printf -- "%s-" "$@"
}
declare -A mda
mda[$(key 1)]=1
mda[$(key 1 a)]=1.a
mda[$(key 2 k iv)]=2.k.iv
```
This lets you mimic multi-dimensional behavior using a single associative array. It's a little different from traditional multi-dimensional arrays, but it works effectively in Bash!
ArrayExplorer: Thanks for the example! I think I can adapt that to my needs.
Reply to this answer
Add your answer
Answers are reviewed before publication.
HelpfulPal88: Good idea! Using files could definitely keep things organized.