Skip to content

Commit 1335882

Browse files
[Term Entry] Command line Bash: Associative Arrays (#6319)
* [Term Entry] Command line Bash: Associative Arrays * fixed indentation * made suggested changes ---------
1 parent 6b493da commit 1335882

File tree

1 file changed

+190
-0
lines changed

1 file changed

+190
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
---
2+
Title: 'Associative Arrays'
3+
Description: 'Stores and retrieves data using key-value pairs in Bash scripts'
4+
Subjects:
5+
- 'Bash/Shell'
6+
- 'Computer Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Bash/Shell'
10+
- 'Data Structures'
11+
CatalogContent:
12+
- 'learn-the-command-line'
13+
- 'paths/computer-science'
14+
---
15+
16+
**Associative arrays** in Bash are key-value pair [data structures](https://www.codecademy.com/resources/docs/general/data-structures) that allow users to store and retrieve values using unique keys instead of numeric indices. First introduced in Bash version 4, they provide a powerful way to organize and manipulate data in shell scripts.
17+
18+
Associative arrays are particularly useful for creating lookup tables, storing configuration settings, counting occurrences, and organizing complex data in shell scripts. Their ability to use strings as indexes makes them more flexible than traditional indexed arrays when working with named data.
19+
20+
## Syntax
21+
22+
To work with associative arrays in Bash, we need to understand the following syntax elements:
23+
24+
- `declare -A array_name`: Creates an empty associative array. The `-A` option is required to specify an associative array.
25+
- `array_name[key]=value`: Assigns a value to a specific key in the array.
26+
- `${array_name[key]}`: Retrieves the value associated with a specific key.
27+
- `${!array_name[@]}`: Returns all keys in the array.
28+
- `${array_name[@]}`: Returns all values in the array.
29+
- `unset array_name[key]`: Removes a specific key-value pair from the array.
30+
- `unset array_name`: Deletes the entire array.
31+
32+
**Return value:**
33+
34+
Associative arrays return the values associated with the specified keys when accessed.
35+
36+
## Example 1: Creating and populating basic associative arrays
37+
38+
The following example demonstrates how to declare and initialize an associative array in Bash:
39+
40+
```bash
41+
# Declare an associative array
42+
declare -A user_details
43+
44+
# Add key-value pairs
45+
user_details[name]="John Doe"
46+
user_details[email]="[email protected]"
47+
user_details[age]=30
48+
user_details[role]="Developer"
49+
50+
# Print a specific value
51+
echo "Name: ${user_details[name]}"
52+
53+
# Print all keys
54+
echo "Available information: ${!user_details[@]}"
55+
56+
# Print all values
57+
echo "User details: ${user_details[@]}"
58+
```
59+
60+
The output will be as follows:
61+
62+
```shell
63+
Name: John Doe
64+
Available information: name email role age
65+
User details: John Doe [email protected] Developer 30
66+
```
67+
68+
This example demonstrates the creation of an associative array called `user_details`, which stores various pieces of information about a user. The keys are strings (`'name'`, `'email'`, `'age'`, `'role'`), allowing access to specific values using those keys.
69+
70+
## Example 2: Building a configuration manager with associative arrays
71+
72+
Associative arrays are perfect for configuration management in Bash scripts. Here's how they can be used to store and retrieve application settings:
73+
74+
```bash
75+
#!/bin/bash
76+
77+
# Declare an associative array for configuration
78+
declare -A config
79+
80+
# Load configuration values
81+
config[db_host]="localhost"
82+
config[db_port]="3306"
83+
config[db_user]="admin"
84+
config[db_name]="myapp"
85+
config[app_env]="development"
86+
config[debug]="true"
87+
config[log_level]="info"
88+
89+
# Function to get configuration value
90+
get_config() {
91+
local key=$1
92+
local default_value=$2
93+
94+
# If the key exists in the array, return its value
95+
if [[ -n "${config[$key]+x}" ]]; then
96+
echo "${config[$key]}"
97+
else
98+
# Otherwise return the default value
99+
echo "$default_value"
100+
fi
101+
}
102+
103+
# Usage examples
104+
echo "Database Host: $(get_config db_host)"
105+
echo "Log Level: $(get_config log_level 'warning')"
106+
echo "Cache Time: $(get_config cache_time '3600')" # Doesn't exist, will use default
107+
108+
# Check if debug mode is enabled
109+
if [[ "$(get_config debug)" == "true" ]]; then
110+
echo "Debug mode is enabled"
111+
fi
112+
```
113+
114+
The output will be as follows:
115+
116+
```shell
117+
Database Host: localhost
118+
Log Level: info
119+
Cache Time: 3600
120+
Debug mode is enabled
121+
```
122+
123+
This example demonstrates using an associative array to manage configuration settings. The `get_config` function retrieves values by key and provides default values for missing keys, making the configuration system robust and flexible.
124+
125+
## Example 3: Creating a word frequency counter with associative arrays
126+
127+
Associative arrays are excellent for counting and tracking occurrences. Here's how to build a simple word frequency counter:
128+
129+
```bash
130+
#!/bin/bash
131+
132+
# Declare an associative array for word counts
133+
declare -A word_counts
134+
135+
# Sample text to analyze
136+
text="Bash scripting is powerful. Bash allows automation of repetitive tasks.
137+
Learn Bash to become more efficient at command line tasks."
138+
139+
# Convert to lowercase and split into words
140+
for word in $(echo "$text" | tr '[:upper:]' '[:lower:]' | tr -d '.' | tr ' ' '\n'); do
141+
# Skip empty words
142+
if [[ -z "$word" ]]; then
143+
continue
144+
fi
145+
146+
# Increment the count for this word
147+
if [[ -z "${word_counts[$word]}" ]]; then
148+
word_counts[$word]=1
149+
else
150+
((word_counts[$word]++))
151+
fi
152+
done
153+
154+
# Print the results
155+
echo "Word frequency analysis:"
156+
echo "-----------------------"
157+
158+
# Sort words by frequency (highest first)
159+
for word in "${!word_counts[@]}"; do
160+
echo "$word: ${word_counts[$word]}"
161+
done | sort -rn -k2
162+
```
163+
164+
Output:
165+
166+
```shell
167+
Word frequency analysis:
168+
-----------------------
169+
bash: 3
170+
to: 2
171+
tasks: 2
172+
powerful: 1
173+
of: 1
174+
more: 1
175+
line: 1
176+
learn: 1
177+
is: 1
178+
efficient: 1
179+
command: 1
180+
become: 1
181+
at: 1
182+
automation: 1
183+
allows: 1
184+
scripting: 1
185+
repetitive: 1
186+
```
187+
188+
This example showcases how associative arrays can be used to count word frequencies in a text. The array keys are words, and the values are the number of occurrences. This pattern is commonly used in text processing and log analysis.
189+
190+
To further enhance your Bash scripting skills, consider taking our [Learn Bash Scripting](https://www.codecademy.com/learn/bash-scripting) course.

0 commit comments

Comments
 (0)