The code and data behind xeiaso.net
5
fork

Configure Feed

Select the types of activity you want to include in your feed.

notes: bash has hashmaps, oh god

Signed-off-by: Xe Iaso <me@xeiaso.net>

Xe Iaso 7904f8ce f555dd9b

+75
+75
lume/src/notes/2024/bash-hashmap.mdx
··· 1 + --- 2 + title: Today I learned that bash has hashmaps 3 + date: 2024-01-15 4 + tags: 5 + - bash 6 + - til 7 + - crimes 8 + --- 9 + 10 + Hashmaps (associative arrays) are a great way to store a bag of key-value data. At work I was writing something that needed me to spawn a bunch of GPU instances, GPU availability is spread out by region and GPU type. I wanted to store a mapping of GPU kind to region name and for some reason I thought it would be a good idea to do it in bash. I was horrified to find out that bash has hashmaps, and decided to write this note to tell you how to use them. 11 + 12 + Here's how you do it: 13 + 14 + First, declare the hashmap with the `declare` builtin: 15 + 16 + ```shell 17 + # -A means associative array (hashmap) 18 + declare -A FLY_REGIONS 19 + ``` 20 + 21 + Then add some values into it [from the fly.io documentation](https://fly.io/docs/gpus/gpu-quickstart/): 22 + 23 + ```shell 24 + FLY_REGIONS["a100-40gb"]="ord" 25 + FLY_REGIONS["a100-80gb"]="mia" 26 + FLY_REGIONS["l40s"]="ord" 27 + ``` 28 + 29 + You can also predeclare the array with values in a read-only state: 30 + 31 + ```sh 32 + # -A means associative array (hashmap) 33 + # -r means read-only 34 + declare -A -r FLY_REGIONS=( 35 + ["a100-40gb"]="ord" 36 + ["a100-80gb"]="mia" 37 + ["l40s"]="ord" 38 + ) 39 + ``` 40 + 41 + You can look up values with the same syntax you used to set them: 42 + 43 + ```shell 44 + echo "${FLY_REGIONS["a100-40gb"]}" # ord 45 + ``` 46 + 47 + You can iterate over the keys with a `for` loop on the `@` value: 48 + 49 + ```shell 50 + for size in "${!FLY_REGIONS[@]}"; do 51 + echo "size: $size, region: ${FLY_REGIONS[$size]}" 52 + done 53 + ``` 54 + 55 + You can iterate over the values with a `for` loop on the `*` value: 56 + 57 + ```shell 58 + for region in "${FLY_REGIONS[@]}"; do 59 + echo "region: $region" 60 + done 61 + ``` 62 + 63 + You can delete individual keys with `unset`: 64 + 65 + ```shell 66 + unset FLY_REGIONS["a100-40gb"] 67 + ``` 68 + 69 + If you need to delete the entire hashmap, you can also do it with `unset`: 70 + 71 + ```shell 72 + unset FLY_REGIONS 73 + ``` 74 + 75 + Please don't use this for evil.