1
0
Fork 0
digitalstudium.com/content/en/bash-lifehacks/bash-arrays-and-hashmaps.md

68 lines
1.4 KiB
Markdown
Raw Normal View History

2023-05-08 15:46:26 +00:00
---
title: "BASH: arrays and hashmaps"
category: bash-lifehacks
filename: bash-arrays-and-hashmaps
date: 2023-05-07T13:35:26.956Z
---
Sometimes there is a need to use in BASH such structures as lists (also known as arrays) and dictionaries (also known as hashmaps and associative arrays). In this post there are some samples how to work with them.
<!--more-->
## 1. Arrays
Array creation in bash can be done this way:
2023-07-23 12:55:12 +00:00
```bash
2023-05-08 15:46:26 +00:00
sample_array=(foo bar bazz)
```
In order to add single or multiple new elements to the end of array, you should use this syntax:
2023-07-23 12:55:12 +00:00
```bash
2023-05-08 15:46:26 +00:00
sample_array+=(six seven)
```
2023-05-12 12:00:52 +00:00
In order to get elements of the list in a cycle, you should use this syntax:
2023-05-08 15:46:26 +00:00
2023-07-23 12:55:12 +00:00
```bash
2023-05-08 15:46:26 +00:00
for i in ${sample_array[@]}
do
echo $i
done
```
Here is an example how to get element by its index:
2023-07-23 12:55:12 +00:00
```bash
2023-05-08 15:46:26 +00:00
echo ${sample_array[0]}
echo ${sample_array[3]}
# 0, 3 etc. - elements' indexes
```
Array slicing:
2023-07-23 12:55:12 +00:00
```bash
2023-05-08 15:46:26 +00:00
sliced_array=${sample_array[@]:1} # will get all elements of a sample_array, starting with 1st
another_sliced_array=${sample_array[@]:1:5} # will get sample_array elements since 1st to 5th
```
## 2. Hashmaps
To create hashmap in bash use this syntax:
2023-07-23 12:55:12 +00:00
```bash
2023-05-08 15:46:26 +00:00
declare -A sample_hashmap=([one]=one [two]=two [three]=three [four]=four [five]=five)
```
This will add new key "foo" with value "bar":
2023-07-23 12:55:12 +00:00
```bash
2023-05-08 15:46:26 +00:00
sample_hashmap[foo]=bar
```
Cycle:
2023-07-23 12:55:12 +00:00
```bash
2023-05-08 15:46:26 +00:00
for key in ${sample_hashmap[@]}
do
echo ${sample_hashmap[$key]}
done
```